1

Probably a very basic question, but the following code fails to replace!

h = '%3c'
c = '<'
s = 'blah %3c blah'
s.replace(h,c)
print(s)

The result is 'blah %3c blah'.

How do I make replace treat %3c as a normal string.

For context, I am HTML encoding and decoding strings by replacing unsafe characters with their %hex representation. I would greatly prefer to use a library for this but haven't been able to find one. As well as answering the above question, the name of such a library would be good.

martineau
  • 119,623
  • 25
  • 170
  • 301
Mark Kortink
  • 1,770
  • 4
  • 21
  • 36
  • 2
    strings are immutable. ``s.replace`` will not modify ``s``, instead you have to work with the result. – Mike Scotty Apr 06 '21 at 22:48
  • You should use `urllib.parse.unquote()` for this rather than `str.replace`. This isn't HTML encoding/decoding, it's URL quoting/unquoting and the difference is important. – Michael Ruth Apr 06 '21 at 23:03

1 Answers1

3

replace returns a new string. Save the new string to the old string.

s = s.replace(h,c)
nbrix
  • 296
  • 2
  • 6