【问题标题】:Extract variable from special string format Python从特殊字符串格式Python中提取变量
【发布时间】:2019-07-11 13:30:36
【问题描述】:

我从 XML 文件中检索了一个字符串,如下所示:

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

(总是相同的格式)

我正在尝试提取两个位置的左值:

left1 = 0
left2 = -143

请问我该怎么做?

【问题讨论】:

  • 按$分割,然后在分割后的item上做json.loads()得到一个列表并访问列表的第一项

标签: python string extract


【解决方案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

【讨论】:

    【解决方案2】:

    如果你想尝试不使用正则表达式

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多