共計 584 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,format()
方法用于格式化字符串。它是一個內(nèi)置的字符串方法,可以通過占位符來指定字符串中的值。
格式化語法如下:
string.format(value1, value2, ...)
其中,string
是要進行格式化的字符串,value1
, value2
, … 是要插入到字符串中的值。
格式化字符串中的占位符使用一對大括號 {}
來表示,可以在占位符中指定值的格式。
以下是一些常見的格式化示例:
- 簡單的占位符
name = "Alice"
age = 20
print("My name is {} and I am {} years old".format(name, age))
輸出:My name is Alice and I am 20 years old
- 指定值的類型
value = 3.14159
print("The value of pi is {:.2f}".format(value))
輸出:The value of pi is 3.14
- 指定占位符的順序
name = "Bob"
age = 25
print("My name is {1} and I am {0} years old".format(age, name))
輸出:My name is Bob and I am 25 years old
這只是 format()
方法的一些基本用法示例,它還支持更多的功能,如對齊、填充、格式化數(shù)字、日期等。詳細的用法可以參考 Python 官方文檔。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完