Reputation: 75
I have a string say:
s = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef'
I could get the data by parsing several XMLs for the items in Parentheses. After obtaining the data, I use dictset's combinator to yield these results(roughly) for the items in parantheses {} :
['ApplC3LDJXGEDCP7', '10']
['ApplC3LDJXGEDCP7', '11']
['ApplC3LDJXGEDCP7', '12']
['ApplC3LDJXGEDCP7', '13']
['androidc1596699510', '14']
Dictset combinations return a list of items [deviceId, groupID]. Considering that I am a newbie to Python, how do I iterate over this list and find/replace items in the string? Please help!
Let me also add what I have tried so far- I could iterate over the list using For and able to replace 1 item from the list using re.sub. However the code needs both the items to be replaced at once. The regex i use is r"{.+?}"
Upvotes: 4
Views: 3272
Reputation: 24439
Use single sub
call and pass a function that returns what you need.
s = 'deviceId={servicename.DeviceID}&deviceGroupID={servicename.GroupID}&abcd=dkef'
r = ['ApplC3LDJXGEDCP7', '10']
print(re.sub(r'{.+?}', lambda match: r.pop(0), s, count=len(r)))
# deviceId=ApplC3LDJXGEDCP7&deviceGroupID=10&abcd=dkef
A better approach may be to use urllib.parse.parse_qs
, that will tolerate parameter reordering, missing parameters, etc.
Upvotes: 3