NotSecondCie NotSecondCie - 1 year ago 96
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)

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.


Answer Source

How about this, using simple regex?

import re

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

>>> Hi, my name is Bob!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download