format()函数格式化字符串?
The format() function in Python is used to format a string by replacing placeholders with variables or values. It is a powerful and flexible method for creating formatted strings.
The basic syntax of the format() function is as follows:
string.format(value1, value2, ...)
The string argument is the string that you want to format, and the values are the placeholders that will be replaced with actual values. The placeholders are identified by curly braces {}, and can include format specifiers that define how the value should be formatted.
The format specifiers are added after the placeholder, separated by a colon. They can contain various options for formatting the value, such as decimal places for numbers, width and alignment for strings, and more.
Here is an example of using the format() function to format a string:
age = 25
name = "John"
print("My name is {} and I am {} years old".format(name, age))
Output:
My name is John and I am 25 years old
In this example, the placeholders {} are replaced with the variables name and age, respectively.
Now let's take a look at the various format specifiers that can be used with the format() function:
1. Positional arguments
You can specify the order of the values by adding numbers inside the curly braces {}, starting from zero.
Example:
print("{1}, {0}".format("World", "Hello"))
Output:
Hello, World
2. Keyword arguments
You can use keyword arguments to assign values to placeholders, using the syntax {key=value}.
Example:
print("My name is {name} and I am {age} years old".format(name="John", age=25))
Output:
My name is John and I am 25 years old
3. Number formatting
You can use format specifiers to format numbers, such as decimal places.
Example:
pi = 3.14159265359
print("Pi is approximately {:.2f}".format(pi))
Output:
Pi is approximately 3.14
4. String formatting
You can use format specifiers to format strings, such as adding padding and adjusting alignment.
Example:
name = "John"
print("My name is {:^10}".format(name))
Output:
My name is John
5. Date formatting
You can use format specifiers to format dates and times.
Example:
from datetime import datetime
now = datetime.now()
print("Today's date is {:%Y-%m-%d}".format(now))
Output:
Today's date is 2021-08-18
In conclusion, the format() function in Python is a powerful tool for formatting strings using various placeholders and format specifiers. By understanding and utilizing its capabilities, you can create more readable and flexible code.
