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"]
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.
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 .
🔹 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.
Use splitlines()
, passing keepends=True
:
"amount\nexceeds".splitlines(keepends=True)
gives you:
["amount\n", "exceeds"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With