2

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

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

例如,是否可以在example1和中获取等号旁边的值example3?只知道关键字,不知道后面是=什么?

4

2 回答 2

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'
于 2013-06-26T19:36:47.560 回答
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']
>>> 
于 2013-06-26T19:48:57.390 回答