I'm not an expert in python and since it's work related i may have to change some variables and info.
So i have a long string from an API request in which I'm looking for the information of users, and to make sure i only have the users info , I use their ID with .find(ID) which show me the index where the ID is in the string ( middle of the user info). After that what i want is to go up the
string and search for the tag that starts the information
`**<resource>** and down to the tag that end the information ****</resource>**.`
**id_position = string.find(id)**
**upper = string[:id_position].rfind("<resource>")** to go in reverse order up the string and find the first match , and works fine
but when i use **lower = string[id_position].find("</resource>")**
, instead of going normally from the id position,down till it finds the first match , it actually searches in the entire original string, as in searching from the first position string[0] onwards.
when i print
**string[:id_position] string[id_position:] == string** ,
it shows it's true, so i'm guessing the find function doesn't help me like i think it should.
So my question is, how can i search for my specific substring after the index of the id ?
I know it's hard to understand but i hope some of you may know what i mean
for reference,the data looks like this
.<resource>
name=
ip=
.</resource>
.<resource>
name2=
ip2=
</resource>
.<resource>
name=
ip2=
.</resource>
CodePudding user response:
Have you tried using find()
s optional parameters start
and end
?
id_position = string.find(id)
upper = string.find("</resource>", id_position) len("</resource>")
lower = string.rfind("<resource>", 0, id_position)
print(repr(string[lower:upper]))
> '<resource>\n name2=\n ip2=\n</resource>'