我是 python 语言的新手,我一直在寻找这个问题的答案。
我需要一个如下所示的列表:
['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.']
转换成如下所示的字符串:
Kevin went to his computer.
He sat down.
He fell asleep.
我需要它的字符串格式,这样我就可以将它写入文本文件。任何帮助将不胜感激。
最佳答案
简短的解决方案:
>>> 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.
关于string - 在python中将列表转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616828/