Reputation: 14681
I'm working on a web application.
I need to escape %
and { }
, if any exists, for further string replacement using either .format()
or %s
I tried urllib quote_plus
, re.escape()
but none works.
The string I need to escape is not static.
How can I solve this issue?
Thank you.
Upvotes: 4
Views: 138
Reputation: 6414
To escape %
, {
and }
. You can do this with the re.sub
method. To escape for string.format
:
re.sub(r'({|})', '\g<1>\g<1>', original)
To escape for string % args
:
re.sub(r'(%)', '\g<1>\g<1>', original)
Upvotes: 0
Reputation: 213115
For usage with %
:
s = s.replace('%', '%%')
For usage with format
:
s = s.replace('{', '{{').replace('}', '}}')
Upvotes: 3