Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string at newline characters

Tags:

python

string

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']
like image 942
Hulk Avatar asked Jan 19 '10 14:01

Hulk


People also ask

How do you split a string in newline?

Split String at Newline Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .

How do you split a string into a new line character in Python?

To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of a newline, "\n" .

How split a string by line in C#?

Using String. NewLine , which gets the newline string defined for the current environment. Another way to split the string is using a Unicode character array. To split the string by line break, the character array should contain the CR and LF characters, i.e., carriage return \r and line feed \n .


1 Answers

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

like image 81
PaulMcG Avatar answered Sep 20 '22 17:09

PaulMcG