Dynamically avoid the% sign and parenthesis {} in a string

I am working on a web application.

I need to exit % and { } , if they exist, to further replace the string with .format() or %s

I tried urllib quote_plus , re.escape() but nobody works.

The line I need to execute is not static.

How can I solve this problem?

Thanks.

+4
source share
2 answers

For use with % :

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

For use with format :

 s = s.replace('{', '{{').replace('}', '}}') 
+3
source

To exit % , { and } . You can do this with the re.sub method. To go beyond string.format :

 re.sub(r'({|})', '\g<1>\g<1>', original) 

To go beyond string % args :

 re.sub(r'(%)', '\g<1>\g<1>', original) 
0
source

All Articles