Selective Escaping of Percent Signs in Python Strings
In Python, the percent sign (%) is used as a placeholder for formatting values into strings. However, in some cases, you may want to selectively escape the percent sign to display it as a literal character instead. This can be achieved by adding an extra percent sign before the one you wish to escape.
Example:
Consider the following code:
test = "have it break." selectiveEscape = "Print percent % in sentence and not %s" % test print(selectiveEscape)
The above code is expected to produce the output:
Print percent % in sentence and not have it break.
However, the actual output will be an error:
TypeError: %d format: a number is required, not str
This error occurs because Python interprets the first percent sign as the start of a formatting placeholder, but the value it finds is a string, not a number.
Solution:
To escape the percent sign and display it as a literal character, an additional percent sign must be added before the one you wish to escape. Here's the corrected code:
selectiveEscape = "Print percent %% in sentence and not %s" % test print(selectiveEscape)
The output of the corrected code will now be:
Print percent % in sentence and not have it break.
The above is the detailed content of How to Properly Escape Percent Signs in Python String Formatting?. For more information, please follow other related articles on the PHP Chinese website!