单词之间加逗号

Put commas between words

如何在字符串中的单词之间放置逗号

我有这样一个字符串:

Zendaya Benedict Cumberbatch Tom Holland

我想在每两个单词之间加一个逗号,因为每两个单词代表一个名字。

一种可能是使用迭代器:

s = 'Zendaya Stoermer-Coleman Benedict Cumberbatch Tom Holland'

words = iter(s.split())
output = ', '.join(f"{x} {next(words)}" for x in words)
print(output) # Zendaya Stoermer-Coleman, Benedict Cumberbatch, Tom Holland

或者,您可以进行切片:

words = s.split()
output = ', '.join(' '.join(words[i:i+2]) for i in range(0, len(words), 2))
print(output) # Zendaya Stoermer-Coleman, Benedict Cumberbatch, Tom Holland