【Python学习】格式化输出--%和format的用法

"%"用法

整数输出%o、%d、%x

举例:

print('%o' % 25)  #八进制输出
print('%d' % 25)  #十进制输出
print('%x' % 25)  #十六进制输出

结果:

31
25
19

浮点数输出%f、%e

%f:默认保留小数点后六位有效数字,输出为小数形式
%.3f:保留小数点后3位有效数字

%e:也是默认保留小数点后6位有效数字,输出为指数形式
%.3e:保留小数点后3位有效数字

举例:

print('%f' % 1.234) 
print('%.2f' % 1.234)
print('%e' % 1.234)
print('%.2e' % 1.234)

结果:

1.234000
1.23
1.234000e+00
1.23e+00

字符串输出%s

%s:字符串输出,也可以跟%f一样利用数字控制输出
%10s:右对齐,10位占位符,不够补位
%-10s:左对齐,10位占位符,不够补位
%10.2s:右对齐,10位占位符,取两位字符

举例:

print('%s' % 'hello world')
print('%15s' % 'hello world')
print('%-15s' % 'hello world')
print('%10.2s' % 'hello world')

结果:

hello world
    hello world
hello world    
        he

"%"组合使用

举例:

name = 'Era'
age = 23
job = 'IT'
salary = 3.5

info = "--------info of %s ------- \n" \
        "Name:%s \n" \
        "Age:%d \n" \
        "Job:%s \n" \
        "Salary:%.2f"%(name,name,age,job,salary)

print(info)

结果:

--------info of Era ------- 
Name:Era 
Age:23 
Job:IT 
Salary:3.50

format()的用法

位置匹配

举例:

name = 'Era'
age = 23
job = 'IT'
salary = 3.5

info = "--------info of {} ------- \n" \
        "Name:{} \n" \
        "Age:{} \n" \
        "Job:{} \n" \
        "Salary:{}".format(name,name,age,job,salary)

print(info)

结果:

--------info of Era ------- 
Name:Era 
Age:23 
Job:IT 
Salary:3.5

索引匹配

举例:

name = 'Era'
age = 23
job = 'IT'
salary = 3.5

info = "--------info of {0} ------- \n" \
        "Name:{0} \n" \
        "Age:{1} \n" \
        "Job:{2} \n" \
        "Salary:{3}".format(name,age,job,salary)#四个参数,按顺序0,1,2,3索引
        
print(info)

结果:

--------info of Era ------- 
Name:Era 
Age:23 
Job:IT 
Salary:3.5

名称匹配

举例:

name = 'Era'
age = 23
job = 'IT'
salary = 3.5

info = "--------info of {_name} ------- \n" \
        "Name:{_name} \n" \
        "Age:{_age} \n" \
        "Job:{_job} \n" \
        "Salary:{_salary}".format(_name = name,
                                  _age = age,
                                  _job = job,
                                  _salary = salary)

print(info)

结果:

--------info of Era ------- 
Name:Era 
Age:23 
Job:IT 
Salary:3.5

format()函数其实功能很多,“%”所能实现的,format()基本能够实现,而且还有其他一些强大的功能,但知识有限,所以就不一一列举了。

你可能感兴趣的:(Python基础)