Python3 多行字符串打印下一个
Python3 Multi-Lined String Print Next
如何使用 next() 函数打印以 "string" 开头的每行下方的行?我只找到了如何从 .txt 文档中找到答案,但我不想在这种情况下使用文本文档。这是我目前所拥有的 tried/have...
longString = """
string1
01
string2
02
string3
03
"""
lines = longString.split('\n')
for line in lines:
if line.startswith(str(mylist[0])): # The mylist[0] is "string"
print(line)
Output:
string1
string2
string3
longString = """
string1
01
string2
02
string3
03
"""
lines = iter(longString.split('\n'))
for line in lines:
if line.startswith("string"):
print(next(lines))
Output:
01
02
03
您需要一个实际的迭代器(不仅仅是一个可迭代序列)来使用 next()
- 而 built-in iter()
函数就是这样做的。
请注意,我必须删除字符串中的前导空格 - none 行实际上以 "string" 开头。
如何使用 next() 函数打印以 "string" 开头的每行下方的行?我只找到了如何从 .txt 文档中找到答案,但我不想在这种情况下使用文本文档。这是我目前所拥有的 tried/have...
longString = """
string1
01
string2
02
string3
03
"""
lines = longString.split('\n')
for line in lines:
if line.startswith(str(mylist[0])): # The mylist[0] is "string"
print(line)
Output:
string1
string2
string3
longString = """
string1
01
string2
02
string3
03
"""
lines = iter(longString.split('\n'))
for line in lines:
if line.startswith("string"):
print(next(lines))
Output:
01
02
03
您需要一个实际的迭代器(不仅仅是一个可迭代序列)来使用 next()
- 而 built-in iter()
函数就是这样做的。
请注意,我必须删除字符串中的前导空格 - none 行实际上以 "string" 开头。