SoFunction
Updated on 2025-04-24

Four common ways to format strings in Python

1. Introduction

In Python programming, formatting strings is a common and important task. It can help us insert variables, expressions, and other content into strings, making the output clearer and easier to read. Python provides a variety of ways to format strings, each with its characteristics and applicable scenarios. This article will introduce in detail four common ways to format strings in Python and explain them with rich code examples.

2. % formatting

2.1 Basic Principles

%Format is the oldest way to format strings in Python, it uses%Operator, according to%The following formatting characters specify the type of the variable and insert the variable into the string.

2.2 Code Example

# Define variablesname = "Alice"
age = 25
# Use % to format the string, %s represents the string type, and %d represents the integer typemessage = "My name is %s and I am %d years old." % (name, age)
print(message)  # Output the formatted string
# Format floating point number, %.2f means retaining two decimal placesheight = 1.65
height_message = "My height is %.2f meters." % height
print(height_message)

In the above code,%sUsed to format strings,%dFormat integers,%.2fUsed to format floating point numbers and retain two decimal places. pass%Operator, inserts variables into corresponding positions.

III. () Method

3.1 Basic Principles

()The method is a way to format strings introduced in Python 2.6, using curly braces{}As a placeholder,format()Parameters in the method to fill the placeholder.

3.2 Code Example

# Define variablesname = "Bob"
age = 30
# Format string using () methodmessage = "My name is {} and I am {} years old.".format(name, age)
print(message)

# Specify the fill order of placeholders through indexmessage_index = "My name is {1} and I am {0} years old.".format(age, name)
print(message_index)

# Specify the fill of placeholders through keyword parametersmessage_keyword = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(message_keyword)

# Format floating point numbers, specify the number of decimal places to be retainedweight = 70.5
weight_message = "My weight is {:.1f} kilograms.".format(weight)
print(weight_message)

In the above code,{}It is the default placeholder, and the fill order and content of the placeholder can also be specified through index or keyword parameters. At the same time, it can also be used:.1fetc. format floating point numbers.

4. f-string (formatted string literal value)

4.1 Basic Principles

f-string is a new way to format strings introduced in Python 3.6, which precedes stringsforFPrefix, using curly braces in strings{}Embed variables or expressions directly.

4.2 Code Example

# Define variablesname = "Charlie"
age = 35
# Format strings using f-stringmessage = f"My name is {name} and I am {age} years old."
print(message)

# Use expressions in f-stringbirth_year = 2023 - age
message_expr = f"I was born in {birth_year}."
print(message_expr)

# Format floating point numberssalary = 5000.75
salary_message = f"My monthly salary is {salary:.2f} yuan."
print(salary_message)

In the above code, by prefixing the stringfPrefix, use variables or expressions directly in curly braces, and Python will automatically replace them with the corresponding value. At the same time, you can also use format specifiers to format variables.

5. Template string

5.1 Basic Principles

The template string is PythonstringIn the moduleTemplateA method of formatting strings provided by the class, which uses$Symbols as placeholders, throughsubstitute()Method to replace placeholders.

5.2 Code Example

from string import Template

# Define variablesname = "David"
age = 40
# Create a template stringtemplate = Template("My name is $name and I am $age years old.")
# Use substitute() method to replace placeholdersmessage = (name=name, age=age)
print(message)

In the above code, first importTemplateclass, then create a template string, using$Symbols define placeholders. Finally, bysubstitute()Method replaces the variable into placeholder.

6. Summary and Outlook

6.1 Summary

Python provides a variety of ways to format strings, each with its advantages and disadvantages:

  • %Format is the oldest way, with simple syntax but not flexible enough.
  • ()The method provides more flexibility, supports indexes, keyword parameters, etc., but the code is relatively verbose.
  • f-string is the simplest and most intuitive way, supports direct embedding of variables and expressions, and has high code readability, but requires Python version 3.6 and above.
  • Template strings provide a safe formatting method for scenarios where data needs to be obtained from user input for formatting.

6.2 Outlook

With the continuous development of the Python language, f-string may become the mainstream way to format strings in the future due to its simplicity and ease of use. At the same time, the security advantages of template strings when processing user input will also be widely used in specific scenarios. Developers can choose the appropriate formatting method according to their specific needs and Python version.

The above is the detailed content of four common ways to format strings in Python. For more information about Python formatting strings, please follow my other related articles!