有很多这样的问题,但他们都在处理文件。我只是在处理一个字符串:
"""
Your username is:
joe
normal
"""
我需要找到"Your username is:“的位置,然后抓取它后面的2行。没有可以使用的file.txt。
发布于 2021-02-03 23:05:09
编辑版本2:
更新代码以反映对输入数据所做的新更改
example ='''This is an example string
That has multiple lines
With the words Your username is:
joe
normal
It should NOT grab this line
However it should detect the next line as it has
Your username is:
jane
also_normal
Do not grab this line'''
grab = False
line_count = 0
for line in example.split('\n'):
if grab == True and line_count < 2:
print (line)
line_count +=1
elif 'Your username is:' in line:
grab = True
line_count = 0
else:
grab = False
line_count = 0
它的输出将是:
joe
normal
jane
also_normal
编辑版本1:
我想你正在寻找一个可以处理多行字符串变量的代码,并给你一个答案。
example ='''This is an example string
That has multiple lines
With the words Your username is: joe normal in the string
Program should grab this first line
And this second line and print
It should NOT grab this line
However it should detect the next line as it has
Your username is: joe normal
Grab this first line again
And grab this second line as well
Do not grab this line'''
grab = False
line_count = 0
for line in example.split('\n'):
if grab == True and line_count < 2:
print (line)
line_count +=1
elif 'Your username is: joe normal' in line:
grab = True
line_count = 0
else:
grab = False
line_count = 0
它的输出将是:
Program should grab this first line
And this second line and print
Grab this first line again
And grab this second line as well
发布于 2021-02-03 22:52:59
你可以用你的用户名来拆分文本:然后检测你的用户名在哪里:然后把下一行移到下面的代码示例
splittext = "Your username is: joe normal".split("Your username is:")
splittext.remove('')
for i in range(0, len(splittext)):
splittext[i] = splittext[i][1:len(splittext[i])]
#returns joe normal
https://stackoverflow.com/questions/66036772
复制相似问题