nadermx nadermx - 5 months ago 17
Python Question

How to remove text between variables

I currently have a string that has variables in it.

domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh


I'm trying to delete

&thingy=(all text that is in here)


The order might not always be that, and the text after the
=
will change.

I started doing something like this, but I feel there has to be quicker alternative:

cleanlist = []
variables = url.split('&')
for t in variables:
if not t.split('=', 1)[0] == 'thingy':
cleanlist.append(t.split('=', 1)[0])

Answer

You can substitute using regex.

import re
p = re.compile(ur'(&thingy=.*)&')
test_str = u"domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh"
subst = u"&"

result = re.sub(p, subst, test_str)

>>> result
u'domain.com/?hello=randomtext&stuff=1231kjh'