【问题标题】:converting a list to a string in python在python中将列表转换为字符串
【发布时间】:2012-11-29 00:24:13
【问题描述】:

我对 python 语言还很陌生,我一直在寻找这个问题的答案。

我需要一个如下所示的列表:

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

转换成如下字符串:

Kevin went to his computer.

He sat down.

He fell asleep.

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

【问题讨论】:

    标签: string list python-3.x


    【解决方案1】:

    短解:

    >>> 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.
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 2016-11-09
      • 1970-01-01
      • 2023-03-16
      • 2017-11-15
      • 2021-12-04
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多