4

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

3
  • 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"\{.+?\}" Commented Aug 17, 2011 at 4:13
  • There is practically the same question asked minutes after: stackoverflow.com/questions/7087905/… Commented Aug 17, 2011 at 4:57
  • hi Eugene, the response uses a dictionary key to iterate. Unfortunately I am unable to add a key to the result given that the result is a list. Let me try, but am not sure whether it will yield results. Commented Aug 17, 2011 at 5:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.