2012-11-29 48 views
3

我对Python语言相当陌生,我一直在寻找一段时间来回答这个问题。将列表转换为Python中的字符串

我需要有一个看起来像一个列表:

['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.'] 

转换成看起来像一个字符串:

Kevin went to his computer. 

He sat down. 

He fell asleep. 

我需要它的字符串格式,所以我可以将其写入文本文件。任何帮助,将不胜感激。

回答

4

简短的解决方案:

>>> l 
['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.'] 

>>> print ' '.join(l) 
Kevin went to his computer. He sat down. He fell asleep. 

>>> print ' '.join(l).replace('. ', '.\n') 
Kevin went to his computer. 
He sat down. 
He fell asleep. 

长期的解决方案,如果你想确保在单词的两端只有时间触发换行符:

>>> l 
['Mr. Smith', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.']  
>>> def sentences(words): 
...  sentence = [] 
... 
...  for word in words: 
...   sentence.append(word) 
... 
...   if word.endswith('.'): 
...    yield sentence 
...    sentence = [] 
... 
...  if sentence: 
...   yield sentence 
... 
>>> print '\n'.join(' '.join(s) for s in sentences(l)) 
Mr. Smith went to his computer. 
He sat down. 
He fell asleep.