Python字符串格式化输出


%使用

基本格式操作

name = "YoungCyan"
age  = 18
text = "欢迎%s " %name
print(text)
text = "%s%s今年%d貌美如花 " %(name, "是帅哥", age)
print(text)
text = "%(name)s今年%(age)d%(w)s" %{"name": "YoungCyan", "age": 18, "w": " Welcom"}
print(text)

显示百分号%

############error#################
text = "已下载90%了"
print(text)
##################################

注: Python3.9.13解释器可正确运行

format

text= "Hello, {0}".format("YoungCyan")
print(text)
text = "{0}, 今年{1}".format("YoungCyan", 23)
print(text)
text = "{0} == {0}".format("YoungCyan")
print(text)
text = "{} ==> {}".format("YoungCyan", 18)
print(text)
text = "{n1} ==> {n2}".format(n1="YoungCyan", n2=18)
print(text)
age = 11
name = "YoungCyan"
text = "{name} == > {age}".format(name=name, age=age)

构建格式化输出模板

text = "我叫{0}, 今年{1}岁"

data1 = text.format("YoungCyan", 23)
data2 = text.format("张三", 18)

print(data1 + "\n" + data2)

text = "我叫%s, 今年%d岁"
data1 = text %("YoungCyan", 23)
data2 = text %("张三", 18)

print(data1 + "\n" + data2)

f"string"

注: Python3.6版本以上支持

text = f"{'YoungCyan'}喜欢{'音乐'}"
print(text)

hobby = "音乐"
name = "YoungCyan"
text = f"{name}喜欢{hobby}, 今年{20 + 3}"
print(text)
#Python 3.8引入
hobby = "音乐"
name = "YoungCyan"
text = f"{name}喜欢{hobby}, 今年{20 + 3=}"
print(text)
#进制转换

number = 100

print(f"100 ==> {number:#b}")
print(f"100 ==> {number:#o}")
print(f"100 ==> {number:#x}")