gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:49:11 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com