简体   繁体   English

将两个字符串连接在一起,但第一行在 Python 中位于同一行

[英]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:如果我有两个字符串ab ,它们的定义如下:

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:所需的 output 为:

Hello World
Some Text

How would I achieve this for an arbitrary number of strings?我将如何实现任意数量的字符串?

You can do the following.您可以执行以下操作。 This splits and rejoins the arguments appropriately:这将适当地拆分并重新加入 arguments:

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:查看一些文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM