Reputation: 2488
I have a string like this:
param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl
I want to remove any parameter from the string above, User will enter parameter name like
param1,param2 etc.
And depending on that, the entire parameter and its value should be removed from the above string.
For example if user wants to remove param3, the result string should look like
param1=1234¶m2=abcd¶m4=ijkl
Thanks in Advance,
Upvotes: 0
Views: 73
Reputation: 15028
Does something like this work?
>>> import re
>>> def removeparam(query, name):
... return re.sub(name + r'=[^&]*(&|$)', '', query).rstrip('&')
...
>>> removeparam('param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl', 'param3')
'param1=1234¶m2=abcd¶m4=ijkl'
I have tested it for both the first and the last parameter, and it seems to behave well with both, as opposed to some of the other proposed solutions.
If you want to remove several parameters at once, put them in a list, and you can do the following:
>>> import functools
>>> unwanted = ['param4', 'param1', 'param3']
>>> functools.reduce(removeparam, unwanted,
... 'param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl')
...
'param2=abcd'
You are left with the only parameter not being removed!
Upvotes: 0
Reputation: 215009
>>> import re
>>> qs = "param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl"
>>> name = "param2"
>>> rx = '(^|&)' + name + '=[^&]*'
>>> re.sub(rx, '', qs)
'param1=1234¶m3=efgh¶m4=ijkl'
It might be better though to use dedicated functions when working with query strings:
>>> import urllib, urlparse
>>> qs = "param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl"
>>> qry = urlparse.parse_qs(qs)
>>> del qry['param2']
>>> urllib.urlencode(qry, True)
'param4=ijkl¶m3=efgh¶m1=1234'
Upvotes: 2
Reputation: 3913
Use re.sub()
:
import re
>>> qs = "param1=1234¶m2=abcd¶m3=efgh¶m4=ijkl"
>>> omit = "param3"
>>> re.sub(r'%s=[^&]+&'%omit,'',qs)
'param1=1234¶m2=abcd¶m4=ijkl'
Upvotes: 0