Home > Backend Development > Python Tutorial > How to Selectively Escape Percent Signs (%) in Python String Formatting?

How to Selectively Escape Percent Signs (%) in Python String Formatting?

DDD
Release: 2024-11-26 03:57:08
Original
1074 people have browsed it

How to Selectively Escape Percent Signs (%) in Python String Formatting?

Escaping Percent (%) Selectively in Python Strings

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

The expected output is:

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

However, the actual result throws an error:

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

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

Output:

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template