在Python中将列表转换为字符串 [英] converting a list to a string in python
本文介绍了在Python中将列表转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是python语言的新手,我一直在寻找这个问题的答案.
I'm fairly new to the python language and I've been looking for a while for an answer to this question.
我需要一个看起来像这样的列表:
I need to have a list that looks like:
['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.']
转换为如下所示的字符串:
converted into a string that looks like:
Kevin went to his computer.
He sat down.
He fell asleep.
我需要使用字符串格式,因此可以将其写入文本文件.任何帮助将不胜感激.
I need it in the string format so I can write it to a text file. Any help would be appreciated.
推荐答案
简短解决方案:
>>> 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.
长期解决方案,如果您只想确保单词结尾处的句点会触发换行符:
Long solution, if you want to ensure only periods at the ends of words trigger line breaks:
>>> 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.
这篇关于在Python中将列表转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文