How to split a python string into newline characters

In python3 in Win7, I read the webpage in line.

Then I want to split the string into a list of newline characters.

I cannot enter a new line in my code as an argument in split (), because I get the syntax error "EOL while scanning a string literal"

If I type \ and n, I get a Unicode error.

Is there any way to do this?

+4
source share
2 answers

Have you tried using str.splitlines()?

From the docs:

str.splitlines([keepends])

, . . , .

,

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
['abc\n', '\n', 'de fg\r', 'kl\r\n']

split(), sep, .

Edit:

, , . , .

+22

a.txt

this is line 1
this is line 2

:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

Linux, , , \r\n Windows,

+1

Source: https://habr.com/ru/post/1544701/


All Articles