Home > Backend Development > Python Tutorial > How to Properly Escape Percent Signs in Python String Formatting?

How to Properly Escape Percent Signs in Python String Formatting?

Barbara Streisand
Release: 2024-11-29 00:49:12
Original
966 people have browsed it

How to Properly Escape Percent Signs in Python String Formatting?

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)
Copy after login

The above code is expected to produce the output:

Print percent % in sentence and not have it break.
Copy after login
Copy after login

However, the actual output will be an error:

TypeError: %d format: a number is required, not str
Copy after login

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)
Copy after login

The output of the corrected code will now be:

Print percent % in sentence and not have it break.
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template