Basic usage of Python format

In Python, format()a built-in method for formatting strings. It allows you to create formatted strings by replacing placeholders with actual values. Here are some format()common uses of the method:

Basic usage:

 1.name = "Alice"
 age = 25
 print("My name is {} and I am {} years old.".format(name, age))
 输出:My name is Alice and I am 25 years old.

In the above example, we use the placeholder {}to indicate where the value needs to be inserted, and then format()provide the corresponding value in order through the parameters in the method.

2. Specify parameters through positional index:

name = "Bob"

age = 30

print("My name is {0} and I am {1} years old.".format(name, age))

Output:My name is Bob and I am 30 years old.

In this example, we use {0}and {1}to specify the positional index of the parameter. This allows you to control the order of parameter values, rather than relying solely on their format()order within the method.

3. Specify parameters through keyword parameters:

name = "Charlie"

age = 35

print("My name is {n} and I am {a} years old.".format(n=name, a=age))

Output:My name is Charlie and I am 35 years old.

In this example, we use keyword arguments to specify the parameter's value. In the placeholder, we use the keyword names ( nand a) of the corresponding parameters.

4. Format numbers:

number = 3.14159

print("The value of pi is approximately {:.2f}.".format(number))

Output:The value of pi is approximately 3.14.

In this example, we use the placeholder {: .2f}to specify the format of the floating point number, where .2fmeans two decimal places.

These are just some format()examples of common usage of methods. format()Methods also support more formatting options and modifiers such as alignment, padding, etc. You can learn more about it in the official Python documentation str.format().

Guess you like

Origin blog.csdn.net/m0_68870101/article/details/131658288