【问题标题】:Interleave two multiline strings in Python在 Python 中交错两个多行字符串
【发布时间】:2018-11-06 20:39:27
【问题描述】:

我想完全按照this post 中的内容进行操作,Python 除外。考虑两个字符串:

s1='AAA1
    AAA2
    AAA3'
s2='BBB1
    BBB2
    BBB3'

我想让combine(s1,s2)返回:

s3='AAA1BBB1
    AAA2BBB2
    AAA3BBB3'

您可能认为这些字符串实际上很长,我希望这些过程具有高性能。如果你能帮助我知道如何做到这一点,我将不胜感激。

【问题讨论】:

  • Python 中不允许这种多行字符串语法。你的意思是每行之间有一个换行符并且省略了前导空格?
  • @MichaelButscher 是的。字符串确实是多行的,我想将它们水平堆叠。我并不是说解决方案是微不足道的。这就是我在这里问的原因。

标签: python string


【解决方案1】:

多行字符串在 Python 中用''' 表示。

>>> s1 = '''AAA1
...:AAA2
...:AAA3'''
>>> 
>>> s2 = '''BBB1
...:BBB2
...:BBB3'''

您可以使用str.splitlines 拆分它们并使用zip 交错它们。

>>> strings = [s1, s2]
>>> pairs = zip(*(s.splitlines() for s in strings))
>>> result = '\n'.join(''.join(pair) for pair in pairs)
>>> 
>>> print(result)
AAA1BBB1
AAA2BBB2
AAA3BBB3

使用*args 语法接受任意数量的多行字符串的通用函数可以编写如下。

>>> def combine(*strings):
...:    lines = zip(*(s.splitlines() for s in strings))
...:    return '\n'.join(''.join(line) for line in lines)
>>> 
>>> str1 = '''A
...:D
...:H'''
>>> str2 = '''B
...:E
...:I'''
>>> str3 = '''C
...:F
...:J'''
>>> 
>>> print(combine(str1, str2, str3))
ABC
DEF
HIJ

请注意,zip 将它生成的可迭代对象截断为其最短参数的长度,即结果的行数与传递给combine 的最短多行字符串一样多。

如果您希望字符串具有不同的行数并且需要填充值,您可以使用 itertools 模块中的 zip_longest

【讨论】:

  • 这看起来很棒。让我试试,然后回来找你。
  • 我使用了这个解决方案here in this post 非常感谢。
【解决方案2】:

如果涉及换行符,这可能适用于您想要获得的内容:

s1="AAA1\nAAA2\nAAA3"
s2="BBB1\nBBB2\nBBB3"

ms1 = s1.splitlines()
ms2 = s2.splitlines()

new_list = []

i = 0
while i < 3:
  new_list.append( ms1[i]+ms2[i] )
  i = i + 1

print(new_list)

【讨论】:

  • 在这种情况下使用for i in range(3) 循环可能是一个更好的主意,它已经为您提供了一个自动递增的索引。
【解决方案3】:

使用splitlines() 然后zip 两个列表一起使用

s1="AAA1\nAAA2\nAAA3"
s2="BBB1\nBBB2\nBBB3"

l1 = s1.splitlines()
l2 = s2.splitlines()

print('\n'.join([i+j for i,j in zip(l1,l2)]))

输出

AAA1BBB1
AAA2BBB2
AAA3BBB3

【讨论】:

    猜你喜欢
    • 2011-10-11
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2017-07-22
    相关资源
    最近更新 更多