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

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

DDD
DDDOriginal
2024-11-26 03:57:08976browse

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)

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!

Statement:
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