Python's String Formatting Operator %
Question: What is the function of the % operator when applied to strings in Python?
Answer: The % operator is used for string formatting in Python. It allows you to create formatted strings by inserting values into a specified format.
The basic syntax is:
format % values
The format specifier string (format) contains placeholders (%s, %d, etc.), and the values tuple (values) contains the values to be inserted into these placeholders.
For example:
<code class="python">name = "John" age = 30 formatted_string = "Hi, I'm %s and I'm %d years old." % (name, age) print(formatted_string)</code>
Output:
Hi, I'm John and I'm 30 years old.
In this example, the %s placeholder is replaced with the value of the name variable, and the %d placeholder is replaced with the value of the age variable.
The above is the detailed content of What Does the % Operator in Python Strings Do?. For more information, please follow other related articles on the PHP Chinese website!