string - 在python中将列表转换为字符串

标签 string list python-3.x

我是 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/

相关文章:

c# - String.Contains() : Multiple character - C#

string - 在 Lua 中拆分多字节字符串

c++ - std::vector<const char *> 的赋值效果错误?

python - 为什么在 Python 中创建列表需要更多时间?

python - Django 站点初始数据库迁移期间出现奇怪错误

python - 绘制一系列频率的直方图

数组破坏了 Julia 中的字符串类型

R - 列表与重复项的组合?

c# - 从文本文件中读取特定值并将它们放入列表中

python - 在numpy矩阵中查找具有不同列索引的行式最大值列