共計 795 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 的 format 函數用于格式化字符串,將一個或多個值插入到字符串中。它可以在字符串中指定占位符,然后使用 format 函數將對應的值替換到占位符的位置上。
format 函數的基本語法如下:
formatted_string = " 字符串模板 ".format(value1, value2, ...)
在字符串模板中,可以使用花括號 {} 作為占位符,然后在 format 函數中按順序傳入對應的值來替換這些占位符。
以下是一些常用的用法示例:
- 順序替換
name = "Alice"
age = 25
text = "My name is {} and I am {} years old.".format(name, age)
print(text) # 輸出: My name is Alice and I am 25 years old.
- 根據索引替換
name = "Alice"
age = 25
text = "My name is {0} and I am {1} years old.".format(name, age)
print(text) # 輸出: My name is Alice and I am 25 years old.
- 根據關鍵字替換
name = "Alice"
age = 25
text = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(text) # 輸出: My name is Alice and I am 25 years old.
- 格式化數字
pi = 3.14159265359
formatted_pi = "{:.2f}".format(pi)
print(formatted_pi) # 輸出: 3.14
- 對齊和填充
text = "{:<10}{}".format("left", "right")
print(text) # 輸出: "left right"
以上只是 format 函數的一些常用用法,還有更多的格式化選項可以參考官方文檔。
丸趣 TV 網 – 提供最優質的資源集合!
正文完