Phil
Phil

Reputation: 14681

Dynamically escape % sign and brackets { } in a string

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

Answers (2)

Stuart Wakefield
Stuart Wakefield

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

eumiro
eumiro

Reputation: 213115

For usage with %:

s = s.replace('%', '%%')

For usage with format:

s = s.replace('{', '{{').replace('}', '}}')

Upvotes: 3

Related Questions