Python: iterating over a string containing newline

I have a line separated by newline characters, I need to work with each line individually. Although I could iterate through a for loop. However, this prints each character individually.

Example:

convo = "Bob: Hello \n Sandy: How are you? \n Bob: Confused by a python problem"

for line in convo:
    print(line)

>>> B
>>> o
>>> b
>>> :

What would be the best way to do this?

+4
source share
2 answers

You can use str.splitlines:

>>> convo = "Bob: Hello \n Sandy: How are you? \n Bob: Confused by a python problem"
>>> for line in convo.splitlines():
...     print(line)
...
Bob: Hello
 Sandy: How are you?
 Bob: Confused by a python problem
>>>

From docs :

str.splitlines([keepends])

Returns a list of lines in a line, breaking line boundaries. This method uses the universal approach of new lines to splitting lines. Line breaks are not included in the result list unless specified and true.

+10
source

, str.splitlines():

for line in convo.splitlines():
    print(line)

splitlines() , , .

:

>>> convo = "Bob: Hello \n Sandy: How are you? \n Bob: Confused by a python problem"
>>> for line in convo.splitlines():
...     print(line)
... 
Bob: Hello 
 Sandy: How are you? 
 Bob: Confused by a python problem
+4

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


All Articles