1. 程式人生 > >python 字符串格式化—format

python 字符串格式化—format

big form ood output format ict 使用 orm str

Python2.6 開始,新增了一種格式化字符串的函數 str.format()。使用起來簡單方便,不會遇到使用%時候格式的選擇問題。

按照參數默認順序

>>> "yesday is {}, today is {}".format("saturday", "sunday")
‘yesday is saturday, today is sunday‘
>>>

指定參數順序

>>> "yesday is {0}, today is {1}, good day is {0}".format("saturday", "sunday")
‘yesday is saturday, today is sunday, good day is saturday‘
>>>

指定參數名稱

#!/usr/bin/python

s = "I am a {name}, and study {subject}".format(name="coder", subject="ES")
print s

output:

I am a coder, and study ES

使用字典做參數

# dict
d = {"name": "coder", "subject": "VUE"}
s = "I am a {name}, and study {subject}".format(**d)
print s

output:

I am a coder, and study VUE

使用列表做參數

# list
l = ["coder", "big data"]
s = "I am a {0}, and study {1}".format(*l)
print s

output:

I am a coder, and study big data

python 字符串格式化—format