从字符串中提取值

2024-10-01 17:41:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字符串中提取值,我试图使re.match正常工作,但没有任何运气。字符串是:

'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'

我试过:

^{pr2}$

还有:

'/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'.split(' = ')

我不知道还有什么可以补充或做的。我想检索属性'Value, Max, Step'及其值。有什么办法吗?在

谢谢你的帮助


Tags: 字符串rebin属性matchadsplitopt
3条回答

对于这个特定的字符串,下面将其解析为字典:

s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
d = {}
for pair in [val.split('=') for val in s.split('\r\n')[1:-1]]:
    d[pair[0]] = int(pair[1])
s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
data = {}

for l in s.split('\r\n'):
     if " = " in l:
             k,v = l.split(" = ")
             data[k] = int(v)

print data
>>> s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
>>> bits = s.split('\r\n')
>>> val, max_val, step = [int(bits[i].partition(' = ')[2]) for i in [1, 3, 4]]
>>> val
1800
>>> max_val
3600
>>> step
1

相关问题 更多 >

    热门问题