3

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.

0

1 Answer 1

4

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.