Извлечение переменной из специального формата строки Python - PullRequest
0 голосов
/ 11 июля 2019

Я получил строку из файла XML, которая выглядит следующим образом:

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

(это всегда один и тот же формат)

И я пытаюсь извлечь оба левых значения обеих позиций, чтобы иметь:

left1 = 0
left2 = -143

Как мне это сделать, пожалуйста?

Ответы [ 2 ]

1 голос
/ 11 июля 2019

Если вы хотите попробовать без регулярных выражений

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)
1 голос
/ 11 июля 2019

Вы можете использовать регулярное выражение:

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
...