简体   繁体   中英

How to iterate a list over re.sub and replace variables in a string using python?

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"{.+?}"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM