python进阶(3)字符串格式化
一、使用format函数
语法
str.format(*args,**kwargs)
*args和**kwargs选一个
args
:字符串
kwargs
:键值对(key=value)
例子
代码
Shell
模式
>>> s="{}abc{}def".format("111","222")
>>> s
'111abc222def'
讲解
111填充到索引0
处(默认值为第1个
),222填充到索引1
处(默认值为第2个
)
代码
Shell
模式
>>> s="{1}abc{0}def".format("111","222")
>>> s
'222abc111def'
讲解
111填充到索引0
处(已经设置为第2个
),222填充到索引1
处(已经设置为第1个
)
代码
Shell
模式
>>> s="{a}+{b}={ans}".format(a="2",b="3",ans=5)
>>> s
'2+3=5'
讲解
2填充到键a
处(已经设置为字符串里的{a}
),3填充到键b
处(已经设置为字符串里的{b}
),5填充到键ans
处(已经设置为字符串里的{ans}
)
二、使用%符号
替换类型表
占位符 | 替换类型 |
---|---|
%d | 整数 |
%f | 浮点数 |
%s | 字符串 |
%x | 十六进制整数 |
例子
代码
Shell
模式
>>> s="hello%s"
>>> s
'hello%s'
>>> s%"world"
'helloworld'
讲解
只有一个,可不用括号,'world'
填充到%s
处。
代码
Shell
模式
>>> s="%d-%d-%d"
>>> s
'%d-%d-%d'
>>> s%(2025,5,4)
'2025-5-4'
讲解
有多个,必须用括号,'2025'
填充到第一个%d
处,'5'
填充到第二个%d
处,'4'
填充到第三个%d
处。
三、使用f开头
例子
Shell
模式
>>> num1=100
>>> num2=200
>>> num3=num1+num2
>>> s=f"{num1}+{num2}={num3}"
>>> s
'100+200=300'
把{}里的变量都会自动替换,比如{num1}替换成了num1的值。