Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Split String On Newline And Keep Newline

Is there a way to split a string containing a newline character into a list of strings where the newline character has been retained, eg.

"amount\nexceeds"

would produce

["amount\n", "exceeds"]
like image 746
tnoel999888 Avatar asked Aug 16 '17 10:08

tnoel999888


People also ask

Can you split a string by newline in Python?

Use the str. splitlines() method to split a string on newline characters, e.g. my_list = my_str. splitlines() . The splitlines method splits the string on each newline character and returns a list of the lines in the string.

How do I split a string after a new line?

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 separate a new line in Python?

🔹 In Summary The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


1 Answers

Use splitlines(), passing keepends=True:

"amount\nexceeds".splitlines(keepends=True)

gives you:

["amount\n", "exceeds"]
like image 59
Stuart Avatar answered Sep 25 '22 16:09

Stuart