gpt4 book ai didi

Python 获取字符串的位置和接下来的 X 行

转载 作者:行者123 更新时间:2023-12-04 08:09:51 25 4
gpt4 key购买 nike

有很多这样的问题,但他们都在处理文件。我只是在处理一个字符串:

"""
Your username is:
joe
normal
"""
我需要找到“您的用户名是:”的位置,然后捕获它后面的下两行。没有 file.txt 可以使用。

最佳答案

编辑版本 2:
更新了代码以反射(reflect)对输入数据所做的新更改

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

关于Python 获取字符串的位置和接下来的 X 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66036772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com