Home > Article > Backend Development > How to Selectively Escape Percent Signs (%) in Python String Formatting?
In Python strings, the percent sign (%) is often used for string formatting. However, there are scenarios where you want to selectively escape the percent symbol to use it literally in the string.
Consider the following code snippet:
test = "have it break." selectiveEscape = "Print percent % in sentence and not %s" % test print(selectiveEscape)
The expected output is:
Print percent % in sentence and not have it break.
However, the actual result throws an error:
TypeError: %d format: a number is required, not str
This error occurs because the percent sign inside the formatted string %s tries to interpret test as an integer (%d), but test is a string. To escape the percent sign selectively, we can use double percent signs (%%), as seen in the following code:
test = "have it break." selectiveEscape = "Print percent %% in sentence and not %s" % test print(selectiveEscape)
Output:
Print percent % in sentence and not have it break.
The above is the detailed content of How to Selectively Escape Percent Signs (%) in Python String Formatting?. For more information, please follow other related articles on the PHP Chinese website!