简体   繁体   中英

Put commas between words

How to put commas between words in a string

I have such a string:

Zendaya Benedict Cumberbatch Tom Holland

I want to put a comma between every 2 words since every 2 words represent a name.

One possibility is to use an iterator:

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

Alternatively, you can do slicing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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