python 字符串格式化的相關(guān)知識。
我們格式化構(gòu)建字符串可以有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方法或者字典的占位格式化,因為它不會受參數(shù)的位置影響,只需要參數(shù)名稱相同就行。