Three ways formatted output

Three ways formatted output

A placeholder

When writing programs often have: requires the user to enter information, then print in a fixed format

This time will need to use as placeholders: % S (for all data types),% d (only for the number types)

name = 'lh'
age = 19
print('my name is %s my age is %s' % (name, age))

my name is lh my age is 19

age = 19
print('my age is %d' % age)

my age is 19

This method should be familiar with this method for people who have learned the advantages of C / C ++ is.

Two, format format

name = 'lh'
age = 19
print("Hello, {}. You are {}.".format(name, age))

Hello, lh. You are 19.

name = 'lh'
age = 19
print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))

Hello, lh. You are 19-19.

This method is very sad to hear, no one use.

Three, f-String Format

Compared placeholder way, python3.6 version adds f-String formatted way, relatively simple to understand, it is recommended to use this way.

name = "lh"
age = 19
print(f"Hello, {name}. You are {age}."

Hello, lh. You are 19.

Guess you like

Origin www.cnblogs.com/Lin2396/p/11278507.html