Search code examples
pythonpython-3.xstringconcatenation

Concatenate two strings together, but have the first line be on the same line in Python


If I had two strings, a and b, and they were defined as the following:

a = "Hello\nSome"
b = "World\nText"

How would I concatenate them together in such a way that all the characters on the first line would be in the first line on the resultant string, and example:

def Odd_Concat_Function(i1,i2):
   [...]
[...]
c = Odd_Concat_Function(a,b)
print (c)

With the desired output being:

Hello World
Some Text

How would I achieve this for an arbitrary number of strings?


Solution

  • You can do the following. This splits and rejoins 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
    

    You can make it more general to allow any number of such strings:

    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
    

    See some of the docs: