0

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

4
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by bvdet
0

well split() by default removes all whitespace/newlines, so pass it a specific delimiter, i.e.

string = "Hello,\nWorld"
print string.split(",")
0

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

0

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']
"""
0

The string method splitlines() can preserve trailing newlines.

>>> string.splitlines(1)
['Hello\n', 'World']
>>>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.