在Python中将列表转换为字符串

3

我是一个相对新手的Python语言用户,我已经寻找了一段时间来回答这个问题。

我需要创建一个类似于以下列表的数据结构:

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

被转换成像这样的字符串:
Kevin went to his computer.

He sat down.

He fell asleep.

我需要将其以字符串格式输出,以便写入文本文件。任何帮助将不胜感激。

1个回答

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接