簡體   English   中英

從特殊的字符串格式Python中提取變量

[英]Extract variable from special string format Python

我已經從XML文件中檢索了一個字符串,如下所示:

"[0, 30, -146, 0]$[-143, 30, -3, 0]" #[left, top, right, bottom]

(總是相同的格式)

我正在嘗試提取兩個位置的兩個左值:

left1 = 0
left2 = -143

我該怎么辦?

您可以使用正則表達式:

import re
your_str = "[0, 30, -146, 0]$[-143, 30, -3, 0]" #[left, top, right, bottom]
reg = re.compile("\[(-?\d+),")
list_results = re.findall(reg, your_str)
# ['0', '-143']
# if you always have the same kind of str you can even do
# left1, left2 = map(int, re.findall(reg, your_str))  # map to change from str to int

如果您想嘗試不使用正則表達式

string = "[0, 30, -146, 0]$[-143, 30, -3, 0]"
param = string.split("$") #split your string and get ['[0, 30, -146, 0]', '[-143, 30, -3, 0]']
letf = [] #list of your result

#note that param is a List but 'a' is a String
#if you want to acces to first element with index you need to convert 'a' to as list
for a in param:
    b = eval(a) #in this case'eval()' is used to convert str to list
    letf.append(b[0]) #get the first element of the List

print(letf)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM