一个接一个地连接字符串

2024-04-19 20:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中用一个字符连接两个或多个字符串?你知道吗

例如

a = 'hello'
b = 'world'

output = 'hweolellod'

三个或更多的字符串也是如此。使用+是没有帮助的。你知道吗


Tags: 字符串helloworldoutput字符hweolellod
2条回答

一种方法是将str.joinitertools一起使用:

from itertools import chain, zip_longest

a = 'hello'
b = 'world'

zipper = zip_longest(a, b, fillvalue='')
res = ''.join(list(chain.from_iterable(zipper)))

print(res)

hweolrllod

解释

  • zip_longest用于解释长度不一致的字符串。你知道吗
  • zipper这里是一个惰性迭代器,它通过索引同时迭代ab的每个字符。你知道吗
  • 列表创建虽然不是必需的,但是使用str.join更有效。你知道吗

你可以试试这个:

''.join([x + y for x, y in zip(a, b)])

它给出:

'hweolrllod'

相关问题 更多 >