How to use the format function in Python

In Python, format()a function is a method for formatting a string. It allows us to create formatted strings by inserting values ​​into placeholders. Here are some format()examples of using functions:

1. Basic usage:

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

output:My name is Alice and I am 25 years old.

In the example above, we used two placeholders {}, filled with the values ​​of the variables nameand age.

2. Position parameter:

fruit1 = "apple"
fruit2 = "banana"
fruit3 = "orange"
print("I like {}, {} and {}.".format(fruit1, fruit2, fruit3))

output:I like apple, banana and orange.

In the above example, we used three placeholders and passed the corresponding parameters in order.

3. Keyword parameters:

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

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

In the above example, we have used keyword arguments to specify the value of the placeholder.

4. Specify the location by index:

print("I have {0} {1} and {1} {0}.".format("apples", "oranges"))

output:I have apples oranges and oranges apples.

In the above example, we can specify the parameter position to use by index.

5. Format numbers:

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

output:The value of pi is approximately 3.14.

In the above example, we use :.2fa precision of 2 that specifies a floating point number.

6. Format date and time:

import datetime
date = datetime.datetime.now()
print("Current date and time: {:%Y-%m-%d %H:%M:%S}".format(date))

output:Current date and time: 2023-06-02 10:15:30

In the above example, we used :%Y-%m-%d %H:%M:%Sto specify the date and time format.

These are just format()some common usage examples of the function, it also provides many other formatting options such as padding characters, alignment, thousands separator, etc.

Dark horse programmer python tutorial, 8 days from entry to proficiency in python, learning python and watching this set is enough

Guess you like

Origin blog.csdn.net/Itmastergo/article/details/132420979