8. Output Formatting

Formatted output

A placeholder (%)

Introduction:

Often, there is a scene in the program: the user to enter information into a fixed format and printing

Such as requiring the user to enter a user name and age, and then print the following format:My name is xxx,my age is xxx.

Obviously, a character string with a comma splice, the user can input the name and age into the end, not placed in the specified location xxx, and the figure must also be str (digital) conversion to string splicing, very the trouble, we have to try.

#代码:
name = 'lwx'
age = 19
print('My name is '+name+',my age is '+str(age))
print('sss'+',sss')
age = 19
print('My name is lwx,my age is '+str(age))
#结果:
My name is lwx,my age is 19
sss,sss
My name is lwx,my age is 19

The above approach looks awkward, cumbersome to use, then you should use the placeholders, such as:

% S (for all data types)

% D (only for the number types)

res = 'my name is %s,my age is %s'%('lwx','18')         # %s(针对所有的数据类型)
print(res)
# my name is lwx,my age is 18
name = 'lwx'
age = 20
print('my name is %s ,my age is %s' %(name ,age))       # %s(针对所有的数据类型)
#执行结果:
my name is lwx ,my age is 20
age = 20
print('my age is %d' %(age))                            # %d(仅仅针对数字类型
#执行结果:
my age is 20
# 传入字典
res = 'my name is %(name)s,my age is %(age)s'%{'name':'lwx','age':'18'}
print(res)
#执行结果:
# my name is lwx,my age is 18

Two .format format

New in Python2 in another format method: format to format, here we introduce its use:

#代码:
name = 'lwx'
age = 20
print("hello,{}.you are {}.".format(name,age))

name = 'lwx'
age = 20
print("Hello, {1}. You are {0}-{0}.".format(age, name))

name = 'lwx'
age = 20
print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))
#结果:
hello,lwx.you are 20.
Hello, lwx. You are 20-20.
Hello, lwx. You are 20-20.


#代码
info_2= '我的名字是{0},{0},我的年龄是{1},{1}'.format('lwx','18')      
#加入序号输出,{}中间的顺序对应后面format()中元素的顺序
print(info_2)
#执行结果
我的名字是lwx,lwx,我的年龄是18,18

Three .f-string formatted

Compared placeholder manner, Python3.6 new version of a method f-string formatted, relatively simple to understand, recommend

#代码
a= input('你是我名字:')
b= input('你的年龄:')
res = f'我的名字是{a},我的年龄是{b}'
print(res)
#执行结果:
# 你是我名字:lwx
# 你的年龄:18
# 我的名字是lwx,我的年龄是18
name= 'lwx'
age = 20
print(
    f'hello,{name}.you are {age}'
)
#执行结果:
#hello,lwx.you are 20
#大写的F也适用
name= 'lwx'
age = 20
print(
    F'hello,{name}.you are {age}'
)
#执行结果:
#hello,lwx.you are 20
#数值应用
#数值倍数
age2 = 19
print(
    f'{age2*2}'
)
#执行结果:38

#保留几位小数,并且四舍五入
salary = 99.6666
print(
    f'{salary:.3f}'
)
#结果:99.667

Guess you like

Origin www.cnblogs.com/LWX-YEER/p/12421147.html