python格式化格式化输出

一、占位符

1、输出整数(%d)

str1 = "the length of the word is %d" %(16)
print(str1)

输出结果:"the length of the word is 16"

2、输出浮点数

str1 = "the length of the word is %f" %(16.5)
print(str1)

输出结果:"the length of the word is 16.500000"

#保留两位小数
str1 = "the length of the word is %.2f" %(16.5)
print(str1)

输出结果:"the length of the word is 16.50"

#输出占位符(浮点数总共占11位)
str1 = "the length of the word is %10.2f" %(16.5)
print(str1)

输出结果:"the length of the word is      16.50"

3、输出字符串

str1 = "the length of %s is %d" %("hello word",len("hello word"))
print(str1)

输出结果:"the length of hello word is 10"

4、万能格式符

str = "%r %r %r %r"

print (str % (1, 2, 3, 4))
print (str % ("one", "two", "three", "four"))
print (str % (True, False, False, True))
print (str % (str, str, str, str))
print (str % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
))

打印结果:
1 2 3 4
'one' 'two' 'three' 'four'
True False False True
'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'
'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

二、format 格式化函数

str = "{} {}".format("hello", "world")
print(str)

打印结果:"hello world"

#设置指定位置

str = "{1} {0} {1}".format("hello", "world")
print(str)

打印结果:"world hello world"

也可以设置参数

#设置字符串参数
print("网站名:{name}, 地址:{url}".format(name="菜鸟教程", url="www.runoob.com"))

打印结果:网站名:菜鸟教程, 地址:www.runoob.com


#设置字典参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))

打印结果:网站名:菜鸟教程, 地址 www.runoob.com


#设置列表索引
my_list = ['菜鸟教程', 'www.runoob.com']
sample_list = ['入门教程', 'www.rumen.com']
print("网站名:{1[0]}, 地址 {1[1]}".format(sample_list,my_list))

打印结果:网站名:菜鸟教程, 地址 www.runoob.com

my_list = ['菜鸟教程', 'www.runoob.com']
sample_list = ['入门教程', 'www.rumen.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(sample_list,my_list))

打印结果:网站名:入门教程, 地址 www.rumen.com

三、f-String格式化

name = "sike"
age = 15
print(f"hello,{name},You are {age}")

打印结果:hello,sike,You are 15


length = 6.78655
print(f"{length:.2f}")

打印结果:6.79

猜你喜欢

转载自blog.csdn.net/dijiaye1/article/details/115352343