mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4mobile wallpaper 5mobile wallpaper 6
129 字
1 分钟
格式化字符串
2026-03-12

格式化字符串#

格式化字符串有三种方法:%和.format和f字符串,目前主流的是f字符串,%差不多被淘汰了!

%的用法#

%已经很old,但是这个在logging模块的使用频率很高

name = "jack"
age=20
aaa = "%a 的年龄是 %s"%(name,age)
print(aaa)
#但是捏,%存在一个问题
tip = (1,2,3)
# qq = "here are %s"%tip
#print(qq)报错not all arguments converted during string formatting
#(tip,) 告诉 Python:“这是一个整体,别解包!”
qq = "here are %s"%(tip,) #这是个固定写法,就是个元组加个逗号
print(qq)

format方法#

这个方法学校里应该都教过吧,我只简单写个例子

a=3.125
b=11.4514
c="{.2f} is from {.2f}".format(a,b)#类似%,起一个占位替换的作用
#同时这里也可以用索引吧{0},{1}

f字符串#

这个最常见,也是python3最推荐的写法

dog = "大胖狗"
a=f"{dog}真的帅"
print(a)
#输出:大胖狗真的帅 😘😘😘😘

更不动啦!!!😭😭😭😭

偷个懒吧。

分享

如果这篇文章对你有帮助,欢迎分享给更多人!

格式化字符串
https://mizuki.mysqil.com/posts/geshihua/
作者
神秘大胖狗
发布于
2026-03-12
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00