我已经从XML文件中检索了一个字符串,如下所示:
"[0, 30, -146, 0]$[-143, 30, -3, 0]" #[left, top, right, bottom]
(格式始终相同)
我正在尝试提取两个位置的两个左值以使其具有:
left1 = 0
left2 = -143
我该怎么做?
答案 0 :(得分:1)
您可以使用正则表达式:
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
答案 1 :(得分:1)
如果您想不使用正则表达式
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)