if i have a string e.g.
string = "Hello\nWorld"
and do
list = string.split()
'\n' would be ignored
how can I preserve '\n' when splitting strings..?
Thanks
Default split() drops whitespace (including newlines), as pointed out. 's paragraph-splitting idea is fine when paragraphs are separated by blank lines, and correctly noted that splitlines() preserves newlines. Below are a couple of practical, different approaches for loading text while keeping \n visible and some edge cases to watch.
A simple, common pattern is to read the file into a list of lines; the file iterator and readlines() keep trailing newline characters (except when the file's final line lacks one):
with open('myfile.txt', 'r') as f:
lines = f.readlines() # each element normally ends with '\n' When splitting an in-memory string on a delimiter but wanting to keep the newline characters as tokens, use a regular expression that captures the separator. re.split will include captured groups in the result, so the \n strings are preserved and can be reattached if needed:
import re
parts = re.split(r'(\r?\n)', text) # text and newline tokens interleaved
lines_with_newline = [parts[i] + parts[i+1] for i in range(0, len(parts)-1, 2)] Notes and cautions: Windows CRLFs (\r\n) are handled by \r?\n or by Python's universal-newline handling; a file's last line may not end with \n, so checks for that are useful. For quick line-preserving behavior splitlines(True) (mentioned by ) is a handy one-liner; for more control over separators and grouping, the re.split approach is more flexible. See the Python docs for str.splitlines, re.split, and file-object methods for details and edge cases (splitlines, re.split, file methods).
Jump to Post— hacker9801 49well split() by default removes all whitespace/newlines, so pass it a specific delimiter, i.e.
string = "Hello,\nWorld" print string.split(",")
well split() by default removes all whitespace/newlines, so pass it a specific delimiter, i.e.
string = "Hello,\nWorld"
print string.split(",") I see.
However, what I am trying to do is load a text file which contains a paragraph that I want to modify with.
how can I load it into a list so that '\n' are preserved?
Thanks..
If your paragraphs are properly separated, you could use something lke this:
text = """\
This is my
first paragraph.
This is my
second paragraph.
This is my
third paragraph.
"""
q = text.split('\n\n')
print q
"""
my output -->
['This is my\nfirst paragraph.',
'This is my\nsecond paragraph.',
'This is my\nthird paragraph.\n']
""" The string method splitlines() can preserve trailing newlines.
>>> string.splitlines(1)
['Hello\n', 'World']
>>> We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.