Python list to string spacing
<p>I have a list such as this</p>

<pre><code>list = ['Hi', ',', 'my', 'name', 'is', 'Bob', '!']
</code></pre>

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

<pre><code>x = ' '.join(list)
print(x)
</code></pre>

<p>which prints</p>

<pre><code>"Hi , my name is Bob !"
</code></pre>

<p>when what I want printed is:</p>

<pre><code>"Hi, my name is Bob!"
</code></pre>

<p>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.</p>

<p>Thanks!</p>

<p>How about this, using simple regex?</p>

<pre><code>import re

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

&gt;&gt;&gt; Hi, my name is Bob!
</code></pre>

python string list