Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

If I have two strings, a and b, and they were defined as follows:

a = "Hello\nSome"

b = "World\nText"

How can I concatenate them as follows:

 if all the characters on the front line would be in the front line on the resultant string, for  example:

def Odd_Concat_Function(i1,i2):

   [...]

[...]

c = Odd_Concat_Function(a,b)

print (c)

I wanted the output like this:

Hello World

Some Text

1 Answer

0 votes
by (36.8k points)
edited by

You can use the splits and rejoins to the arguments appropriately:

def Odd_Concat_Function(i1, i2):

    return "\n".join(" ".join(p) for p in zip(*(x.split("\n") for x in (i1, i2))))

>>> c = Odd_Concat_Function(a,b)

>>> print (c)

Hello World

Some Text

To make more flexible to any string you can do this:

def Odd_Concat_Function(*args):

    return "\n".join(map(" ".join, zip(*(x.split("\n") for x in args))))

>>> print(Odd_Concat_Function('Hello\nSome', 'World\nText', 'more\nstuff'))

Hello World more

Some Text stuff

Do check out Python Data Science Course which helps you understand from scratch 

Browse Categories

...