1.百分号–基本的格式化操作
1.1百分号充当占位符,最常用的%s只带字符串占位符,%d整型占位符
name = ‘流年’
print(“我是%s” % ‘流年啊’)
print(“我是%s” % name)
name = ‘流年’
age = 28
print(“我是%s今年%d岁” % (‘流年啊’, 18))
print(“我是%s今年%d岁” % (name, age))
msg = “我叫%(name)s,今年%(age)d岁” % {‘name’: name, ‘age’: age}
print(msg)
1.2如果百分号只是只带百分比,而非占位符,那么需要俩个%%即原样输出
text = “兄弟,这个片我已经下载了90%了,居然特么的断网了”
print(text)
text = “%s,这个片我已经下载了90%%了,居然特么的断网了” %”兄弟”
print(text)
# 输出:
兄弟,这个片我已经下载了90%了,居然特么的断网了
一旦字符串格式化中存现百分比的显示,请一定要呀加 %% 以实现输出 %。
2.2 format(推荐)
text = “我叫{0},今年18岁”.format(“流年”)
text = “我叫{0},今年{1}岁”.format(“流年”,18)
text = “我叫{0},今年{1}岁,真是的姓名是{0}。”.format(“流年”,18)
text = “我叫{},今年18岁”.format(“流年”)
text = “我叫{},今年{}岁”.format(“流年”,18)
text = “我叫{},今年{}岁,真是的姓名是{}。”.format(“流年”,18,”流年”)
text = “我叫{n1},今年18岁”.format(n1=”流年”)
text = “我叫{n1},今年{age}岁”.format(n1=”流年”,age=18)
text = “我叫{n1},今年{age}岁,真是的姓名是{n1}。”.format(n1=”流年”,age=18)
text = “我叫{0},今年{1}岁”
data1 = text.format(“流年”,666)
data2 = text.format(“ax”,73)
2.3 f 到Python3.6版本,更便捷。
action = “跑步”
text = f”流年喜欢{action},跑完之后满身大汗”
name = “喵喵”
age = 19
text = f”流年的名字叫{name},今年{age}岁”
print(text)
text = f”流年的名字叫喵喵,今年{19 + 2}岁”
print(text)
# 在Python3.8引入
text = f”流年的名字叫喵喵,今年{19 + 2=}岁”
print(text)
# 进制转换
v1 = f”流年今年{22}岁”
print(v1)
v2 = f”流年今年{22:#b}岁”
print(v2)
v3 = f”流年今年{22:#o}岁”
print(v3)
v4 = f”嫂子今年{22:#x}岁”
print(v4)
# 理解
text = f”我是{‘ax’},我爱大铁锤”
name = “ax”
text = f”我是{name},我爱大铁锤”
name = “ax”
text = f”我是{ name.upper() },我爱大铁锤”
# 输出:我是ax,我爱大铁锤
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/python/288602.html