0

I have retrieve a string from an XML file which looks like this :

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

(It is always the same format)

And i'm trying to extract both left values of both positions to have :

left1 = 0
left2 = -143

How can i do this please?

1
  • 1
    split by $, then do a json.loads() on the splitted item to get a list and access the list's first item Commented Jul 11, 2019 at 13:34

2 Answers 2

1

You can use regular expression:

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
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to try without regex

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.