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