NotSecondCie NotSecondCie - 2 months ago 7
Python Question

Python list to string spacing

I have a list such as this

list = [Hi, ,, my, name, is, Bob, !]


I wanted to convert this to a string, and originally, I found on stackoverflow that .join() could be used. So i did:

x = ' '.join(list)
print(x)


which prints

"Hi , my name is Bob !"


when what I want printed is:

"Hi, my name is Bob!"


How do I not add spaces before periods and exclamation points? I want a more general case so that I can for example read in a text file as a list, and convert it to a string.

Thanks!

Answer

How about this, using simple regex?

import re

list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!']
x = re.sub(r' (\W)',r'\1',' '.join(list))
print(x)

>>> Hi, my name is Bob!
Comments