根据字符的位置从Python中提取字符串中的子字符串

时间:2013-09-17 23:49:24

标签: python string substring

我试图从下面的字符串中提取子字符串

   package: name='com.example.tracker' versionCode='1' versionName='1.0'

as string 1:versionCode ='1' 和字符串2:versionName ='1.0'

我使用了str.find('versionCode),它在版本代码中返回'v'的索引,并且我使用字符串长度来访问'1'。但是,有时间版本代码可能是一个两位数字,所以我无法修复数字的位置。有没有办法实现这个目标?

如果字符串是

    package: name='com.example.tracker' versionCode='12' versionName='12.0'

我需要提取12和12.0。 我的实现可以支持单个数字,但数字会有所不同。

 if line.find('versionCode') != -1:
            x = line.find('versionCode') 
            versionCode = line[x+13:x+15] 

3 个答案:

答案 0 :(得分:1)

您需要使用regular expressions来执行此操作。

在以下每一行中,我们使用模式(.*?)在引号内执行非贪婪搜索以提取字符串,然后在group(1)上而不是group(0)上返回对象,因为0返回整个输入字符串的完整匹配,1给出第一个正则表达式捕获组。

import re

packageDetails = "package: name='com.example.tracker' versionCode='1' versionName='1.0'"
name = re.search("name='(.*?)'", packageDetails).group(1)
versionCode = re.search("versionCode='(.*?)'", packageDetails).group(1)
versionName = re.search("versionName='(.*?)'", packageDetails).group(1)

print "package name is :", name
print "version code is :", versionCode
print "version name is :", versionName 

这输出:

package name is : com.example.tracker
version code is : 1
version name is : 1.0

答案 1 :(得分:1)

您可以使用内置方法操作字符串以获取所需的值:

packageDetails = "package: name='com.example.tracker' versionCode='1' versionName='1.0'"
details = packageDetails
params = ['name=', 'versionCode=', 'versionName=']
params.reverse()
values = []
for p in params:
    details, v = details.split(p)
    values.append(v.strip().strip("'"))
values.reverse()

答案 2 :(得分:0)

或者你可以建一本字典:

>>> details = { x.split('=')[0] : x.split('=')[1].strip("'") for x in a.split()[1:] }
>>> details
{
  "name" : "com.example.tracker",
  "versionCode" : "1",
  "versionName" : "1.0"
}
>>> details['name']
"com.example.tracker"
>>> details['versionCode'] == '1'
true

或者如果你不关心剥离“'”

>>> dict(x.split('=') for x in a.split()[1:])
{
  "name" : "'com.example.tracker'",
  "versionCode" : "'1'",
  "versionName" : "'1.0'"
}