user1861653
user1861653

Reputation: 31

converting a list to a string in 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.

Upvotes: 3

Views: 235

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

Short solution:

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

Upvotes: 4

Related Questions