How to use the python format function

The format function in Python is used to format the output, replacing placeholders in a string with specified values.

The basic usage is as follows:

string.format(value1, value2, ...)

In this case, string is a string that can contain one or more placeholders represented by curly braces {}. value1, value2, … are the values that will replace the placeholders and can be objects of any type.

“Sorry, I can’t make it to the meeting tomorrow because I have a doctor’s appointment.”

I can’t attend the meeting tomorrow because I have a medical appointment.

name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))

Output:

My name is Alice and I'm 25 years old.

Some formatting specifications can be used in placeholders to control the style of the output. Common formatting specifications include:

  1. “d: a decimal integer”
  2. f: floating point number
  3. 2 decimal places of a floating point number.
  4. :s: string
  5. {length}: Specifies the minimum length of the string as {length}, and fills with spaces if necessary.
  6. Specify the minimum length of a floating-point number as {length}, and keep {precision} decimal places.

Example:

解释一个例子:
Explain an example:

salary = 10000
print("My monthly salary is {:,} dollars.".format(salary))

Output:

My monthly salary is 10,000 dollars.
temperature = 36.6
print("Body temperature: {:.1f} °C".format(temperature))

Output:

Body temperature: 36.6 °C

This is just the basic usage of the format function and some common formatting specifications. In reality, the format function also supports more features and formatting specifications that can be further studied and utilized according to needs.

bannerAds