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', 'compu
Solution 1:
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.']
>>>defsentences(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.
Post a Comment for "Converting A List To A String In Python"