Reputation: 34170
I have a string, say
a = "Show details1\nShow details2\nShow details3\nShow details4\nShow details5\n"
How do we split the above with the delimiter \n
(a newline)?
The result should be
['Show details1', 'Show details2', ..., 'Show details5']
Upvotes: 18
Views: 31174
Reputation: 81
Had a similar issue. I was getting csv data in this format
["User Name\r\nEmail\r\nContact\nAddress", "Name 1\r\[email protected]\r\n+12345657890\r\nSample Address", "Name 2\r\[email protected]\r\n+21345657890\r\nSample Address 2", ]
I used [i.splitlines() for i n data]
to convert in list of list
>>> data = ["User Name\r\nEmail\r\nContact\nAddress", "Name 1\r\[email protected]\r\n+12345657890\r\nSample Address", "Name 2\r\[email protected]\r\n+21345657890\r\nSample Address 2", ]
>>> [i.splitlines() for i in data]
[['User Name', 'Email', 'Contact', 'Address'], ['Name 1', '[email protected]', '+12345657890', 'Sample Address'], ['Name 2', '[email protected]', '+21345657890', 'Sample Address 2']]
Upvotes: 0
Reputation: 2299
a.split('\n')
would return an empty entry as the last member of the list.so use
a.split('\n')[:-1]
Upvotes: 1
Reputation: 54464
If you are concerned only with the trailing newline, you can do:
a.rstrip().split('\n')
See, str.lstrip() and str.strip() for variations.
If you are more generally concerned by superfluous newlines producing empty items, you can do:
filter(None, a.split('\n'))
Upvotes: 18
Reputation: 63709
Use a.splitlines()
. This will return you a list of the separate lines. To get your "should be" result, add " ".join(a.splitlines())
, and to get all in lower case as shown, the whole enchilada looks like " ".join(a.splitlines()).lower()
.
Upvotes: 22