格式化输出的三种方式

一、占位符(%)

引入:程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式

比如要求用户输入用户名和年龄,然后打印如下格式:My name is xxx,my age is xxx.

很明显,用逗号进行字符串拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接,非常之麻烦,我们来试一试。

#代码:
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

上面的方法看起来很别扭,使用很麻烦,这时就要使用到占位符,如:

%s(针对所有的数据类型)

%d(仅仅针对数字类型)

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

二、format格式化

在Python2中新增了另一种格式化方法:format格式化,下面我们介绍它的使用方法:

#代码:
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

#其它用法
# 字符填充
print('{x:*<10}'.format(x='填充字符'))      #X的内容在左边
print('{x:*>10}'.format(x='填充字符'))      #X的内容在右边
print('{x:*^10}'.format(x='填充字符'))      #X的内容在中间
#执行结果:
填充字符******
******填充字符
***填充字符***

三、f-string格式化

相比较占位符的方式,Python3.6版本中新增了f-string格式化的方法,比较简单易懂,推荐使用

#代码
a= input('你是我名字:')
b= input('你的年龄:')
res = f'我的名字是{a},我的年龄是{b}'
print(res)

#执行结果:
你是我名字:lwx
你的年龄:18
我的名字是lwx,我的年龄是18



a=input("age:")
print(f'age is {{a}}')
#执行结果:
age:3
age is {a}
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

注意:format的效率最高,并且比%简洁

posted @ 2019-07-26 14:29  祥SHAO  阅读(470)  评论(0编辑  收藏  举报