我有一个由换行符分隔的字符串,我需要单独处理每一行。我虽然可以通过使用for循环迭代。但是,这会分别打印每个角色。
示例:
convo = "Bob: Hello \n Sandy: How are you? \n Bob: Confused by a python problem"
for line in convo:
print(line)
>>> B
>>> o
>>> b
>>> :
最好的方法是什么?
答案 0 :(得分:14)
您可以使用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
>>>
来自docs:
str.splitlines([keepends])
返回字符串中的行列表,在行边界处断开。这种方法 使用通用换行方法来分割线条。除非给出了keepends并且为true,否则换行符不会包括在结果列表中。
答案 1 :(得分:5)
使用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