Python:迭代包含换行符的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22918013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: iterate over a string containing newlines
提问by Chris Headleand
I have a string separated by newline characters, I need to work with each line individually. I though I would be able to iterate over by using a for loop. However this prints each character individually.
我有一个由换行符分隔的字符串,我需要单独处理每一行。我虽然可以使用 for 循环进行迭代。但是,这会单独打印每个字符。
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?
什么是最好的方法来做到这一点?
回答by Martijn Pieters
Split the string by newlines using str.splitlines()
:
使用换行符拆分字符串str.splitlines()
:
for line in convo.splitlines():
print(line)
where splitlines()
uses universal newlinesto split the string, meaning that it'll support line separator conventions of different platforms.
wheresplitlines()
使用通用换行符来分割字符串,这意味着它将支持不同平台的行分隔符约定。
Demo:
演示:
>>> 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
回答by Martijn Pieters
You can use str.splitlines
:
您可以使用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 the docs:
从文档:
str.splitlines([keepends])
Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.
str.splitlines([keepends])
返回字符串中的行列表,在行边界处断开。此方法使用通用换行方法来分割行。结果列表中不包含换行符,除非给出了 keepends 并且为 true。