python格式化输出的三种方式

格式化输出的三种方式

一、占位符(第一种格式化输出 )(3.0版本使用)

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

比如要求用户输入用户名和年龄,然后打印如下格式:

My name is xxx,my age is xxx.

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

但是用占位符就很简单,如:%s(针对所有数据类型),%d(仅仅针对数字类型)

name = 'python'
age = 30
print('My name is %s, my age is %s' % (name, age))
#输出:
My name is python, my age is 30

age = 30
print(' my age is %s' % age)
#输出:
 my age is 30

二、format格式化(第二种格式化输出)(3.4版本,具有向上兼容)

name = 'python'
age = 30
print("hello,{},you are {}".format(name,age))
#输出:
hello,python,you are 30
name = 'python'
age = 30
print("hello,{1},you are {0}-{0}".format(age,name))#索引是根据format后的数据进行的哦
#输出:
hello,python,you are 30-30
name = 'python'
age = 30
print("hello,{name},you are {age}".format(age=age, name=name))
#输出:
hello,python,you are 30

三、f-String格式化(第三种格式化输出)(3.6版本,具有向上兼容)建议使用

比较简单,实用

f 或者 F都可以哦

让字符和数字能够直接相加哦

name = 'python'
age = 30
print(f"hello,{name},you are {age}")
#输出:
hello,python,you are 30

name = 'python'
age = 30
print(F"hello,{name},you are {age}")
输出:
hello,python,you are 30
name = 'python'
age = 30
print(F"{age * 2}")
输出:
60

使打印更加好看

fac = 100.1001
print(f"{fac:.2f}")  # 保留小数点后俩位
#保存在*右边,*20个,fac占8位,剩余在右边,*可替换
print(f"{fac:*>20}")
print(f"{fac:*<20}")
print(f"{fac:*^20}")
print(f"{fac:*^20.2f}")


#输出:
100.10
************100.1001
100.1001************
******100.1001******
*******100.10*******
posted @ 2019-07-31 15:58  豆瓣酱瓣豆  阅读(2404)  评论(0编辑  收藏  举报