Python —— %s、%d、%f + format()

Python —— %s、%d、%f + format()

%s、%d、%f

# 打印字符串(拼接内容)
print("hello,%s" % "Clare")
# hello,Clare

# 打印整数
print("He is %d years old" % 5)
# He is 5 years old

# 打印浮点数
print("His height is %fm." % (1.78))
# His height is 1.780000m.
print("His height is %.2fm." % 1.78)  # .2表示保留小数点后两位
# His height is 1.78m.

# 指定占位符宽度
print("Name:%7s Age:%7d Height:%7.2fover" % ("Clare", 22,1.60))  # 表示总共占7位,
# Name:  Clare Age:     22 Height:   1.60over

# 指定占位符宽度(左对齐)
print("Name:%-7s Age:%-7d Height:%-7.2fover" % ("Clare", 22,1.60))
# Name:Clare   Age:22      Height:1.60   over

# 指定占位符(只能用0做占位符)
print("Name:%07s Age:%07d Height:%07.2fover" % ("Clare", 22,1.60))
# Name:  Clare Age:0000022 Height:0001.60over

# 科学技术法
print(format(0.0015,".2e"))
# 1.50e-03

 格式化函数 format() 

python2.6开始,新增格式化字符串的函数 str.format(),增强了格式字符串的功能。基本语法是通过 "{}" 和 ":" 来代替以前的 "%"。

format()参数可以接受不限个参数,位置可以不按照顺序。

按照位置格式化

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

设置参数格式化 [赋值、通过字典设置、通过列表索引设置]

print("{name}, {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("{name}, {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("{0[0]}, {0[1]}".format(my_list))  # "0" 是必须的

也可以向str.format()传入对象

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

 format() + %f 格式化数字

 

 

 

 


  

 

posted @ 2020-10-19 10:43  乖巧Clare  阅读(612)  评论(0编辑  收藏  举报