Python中格式化构建字符串的方法


发布日期 : 2026-01-08 07:53:55 UTC

访问量: 146 次浏览

Python中格式化构建字符串可以有3种方法:

元组占位符

m = 'python'
astr = 'i love %s' % m
print (astr)
字符串的format方法
m = 'python'
astr = "i love {python}".format(python=m)
print (astr)

字典格式化字符串

m = 'python'
astr = "i love %(python)s " % {'python':m}
print (astr)
大家可以根据自己的实际情况来选择合适的方法,推荐用字符串的format方法或者字典的占位格式化,因为它不会受参数的位置影响,只需要参数名称相同就行。