'How to split a string into multiple lines in python?
I am a newbie in Python. I am trying to write a program that prints the following three words (without punctuation) on three separate lines: first, second, third
m = 'first, second, third'
no_punct = ''
for x in m :
if x != ',':
no_punct+= x
k = no_punct.strip()
print(k)
This is the output I had from the above program:
first second third
Solution 1:[1]
You can print new lines by using '\n'. So you need to replace "," with '\n'.
m.replace(',', '\n')
print(m)
Solution 2:[2]
You can use split to remove space, and put each element in a list, then iterate over the list and use strip to remove the occasional ',' char:
m = 'first, second, third'
for x in m.split():
print(x.strip(','))
first
second
third
Demo:
>>> m = 'first, second, third'
>>> y = m.split()
>>> y
['first,', 'second,', 'third']
>>> y[0].strip(',')
'first'
Solution 3:[3]
If the pattern between words is consistently a comma followed by a space, then you can split by a comma and a space like the following:
>>> m = 'first, second, third'
>>> m.split(', ')
['first', 'second', 'third']
>>>
Then once it's split, you can take the elements and join them with a newline, and print the result:
>>> print('\n'.join(m.split(', ')))
first
second
third
Solution 4:[4]
Instead of storing it in one variable, you can print it immediately.
for x in m :
if x != ',':
no_punct+= x
else:
print(no_punct.strip())
no_punct = ""
A one-liner can be
print(*[x.strip() for x in m.split(',')], sep='\n')
Solution 5:[5]
A simple solution would be like this:
m = 'first, second, third'
print (m.replace(', ', '\n'))
make sure to include the space after the comma in the replace or you will end up with indents.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Richard Dodson |
| Solution 4 | |
| Solution 5 | Andrew Brent Gossage |
