Home  >  Article  >  Backend Development  >  What Does the String Formatting Operator % Do in Python?

What Does the String Formatting Operator % Do in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-21 12:12:02364browse

What Does the String Formatting Operator % Do in Python?

Understanding the String Formatting Operator % in Python

In Python, the % operator serves a crucial role in string formatting. It allows you to create formatted strings by substituting variables or values into placeholders within a string template.

When used with a string on the left-hand side, the % operator operates as a string formatter. It expects a string containing placeholders followed by values to be substituted. The syntax for string formatting is as follows:

format % values

Here, format is the template string containing placeholders (%s, %d, etc.), and values are the values to be substituted into the placeholders.

For instance, consider the following code:

<code class="python">name = "John"
age = 30
message = "Hello %s! You are %d years old." % (name, age)
print(message)</code>

In this example, message is the template string with two placeholders, %s (for string) and %d (for integer). The placeholder %s is substituted with the value of name, while %d is substituted with the value of age. The resulting formatted string is then stored in message and printed.

Therefore, the % operator enables dynamic string manipulation, making it a versatile tool for generating formatted strings with embedded variables or values.

The above is the detailed content of What Does the String Formatting Operator % Do in Python?. 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