I am new to Python so I have lots of doubts. For instance I have a string:
string = "xtpo, example1=x, example2, example3=thisValue"
For example, is it possible to get the values next to the equals in example1 and example3? knowing only the keywords, not what comes after the = ?
Óscar López
237k38 gold badges321 silver badges391 bronze badges
2 Answers 2
You can use 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'
answered Jun 26, 2013 at 19:36
Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
karthikr
This is not what the OP is asking for.
Ashwini Chaudhary
@karthikr I am still not sure what OP is looking for, question is quite unclear.
Brian
@karthikr Actually I think it is, although the question could be worded better
Kevin
@karthikr, I disagree.
x and thisValue are the values next to the equals signs. So it's exactly what the OP asked for.Zebedeu
Sorry for being specific. However I think this what I am looking for. Tomorrow I´ll try in the "real" world" scenario :)
Spacing things out for clarity
>>> 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']
>>>
answered Jun 26, 2013 at 19:48
Steve Barnes
28.6k6 gold badges68 silver badges80 bronze badges
Comments
lang-py
x.split()[-1].split('=')where x is your string