Home > Software design >  Put commas between words
Put commas between words

Time:11-25

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.

CodePudding user response:

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
  • Related