获取字符串中的值 - Python

时间:2013-06-26 19:33:19

标签: python string parsing python-2.7

我是Python的新手,所以我有很多疑问。例如,我有一个字符串:

string = "xtpo, example1=x, example2, example3=thisValue"

例如,是否可以在example1example3中获取等于旁边的值?只知道关键字,而不是=后的内容?

2 个答案:

答案 0 :(得分:2)

您可以使用regex

>>> import re
>>> strs = "xtpo, example1=x, example2, example3=thisValue"
>>> key = 'example1'
>>> re.search(r'{}=(\w+)'.format(key), strs).group(1)
'x'
>>> key = 'example3'
>>> re.search(r'{}=(\w+)'.format(key), strs).group(1)
'thisValue'

答案 1 :(得分:1)

为了清晰起见,将事情分开

>>> Sstring = "xtpo, example1=x, example2, example3=thisValue"
>>> items = Sstring.split(',') # Get the comma separated items
>>> for i in items:
...     Pair = i.split('=')  # Try splitting on =
...     if len(Pair) > 1:    # Did split
...         print Pair       # or whatever you would like to do
... 
[' example1', 'x']
[' example3', 'thisValue']
>>>