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>To solve it in a general case, use the <code>nltk</code>'s <a href="https://github.com/nltk/nltk/pull/1282" rel="nofollow">"moses" detokenizer</a>:</p>

<pre><code>In [1]: l = ["Hi", ",", "my", "name", "is", "Bob", "!"]

In [2]: from nltk.tokenize.moses import MosesDetokenizer

In [3]: detokenizer = MosesDetokenizer()

In [4]: detokenizer.detokenize(l, return_str=True)
Out[4]: u'Hi, my name is Bob!'
</code></pre>

<p>The detokenizer is not yet a part of a stable <code>nltk</code> package. To be able to use it now, install <code>nltk</code> directly from github.</p>

python string list