我不是 python 專家,因為它與作業相關,我可能不得不更改一些變數和資訊。
所以我有一個來自 API 請求的長字串,我在其中尋找用戶的資訊,并確保我只有用戶資訊,我將他們的 ID 與 .find(ID) 一起使用,這向我顯示了ID 在字串中(用戶資訊的中間)。在那之后我想要的是
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>")**
,而不是正常地從 id 位置向下直到找到第一個匹配,它實際上在整個原始字串中搜索,就像從第一個位置string[0]開始搜索一樣。
當我列印
**string[:id_position] string[id_position:] == string** ,
它表明這是真的,所以我猜 find 功能并沒有像我認為的那樣幫助我。
所以我的問題是,如何在 id 的索引之后搜索我的特定子字串?
我知道這很難理解,但我希望你們中的一些人能明白我的意思
供參考,資料看起來像這樣
.<resource>
name=
ip=
.</resource>
.<resource>
name2=
ip2=
</resource>
.<resource>
name=
ip2=
.</resource>
uj5u.com熱心網友回復:
您是否嘗試過使用find()s 可選引數start和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>'
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418884.html
標籤:
上一篇:解壓縮字串,重復字符`n`次
