共計 827 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Python 中,可以使用 format()
方法來格式化字符串。format()
方法可以在字符串中插入變量或值,并根據指定的格式進行格式化。
具體使用方式如下所示:
- 使用位置參數:可以使用
{}
作為占位符,然后通過format()
方法傳遞變量或值來替換占位符。
name = "Alice"
age = 25
print("My name is {}, and I am {} years old.".format(name, age))
# 輸出:My name is Alice, and I am 25 years old.
- 使用關鍵字參數:可以在占位符中使用變量名,并通過
format()
方法使用關鍵字參數來替換占位符。
name = "Bob"
age = 30
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))
# 輸出:My name is Bob, and I am 30 years old.
- 使用索引:可以在占位符中使用索引來指定傳入的變量或值的位置。
name = "Charlie"
age = 35
print("My name is {0}, and I am {1} years old.".format(name, age))
# 輸出:My name is Charlie, and I am 35 years old.
- 使用格式化選項:可以在占位符中使用格式化選項來指定輸出的格式。
pi = 3.14159
print("The value of pi is approximately {:.2f}.".format(pi))
# 輸出:The value of pi is approximately 3.14.
以上是 format()
方法的基本用法,還可以使用其他更多的格式化選項來滿足不同的需求。具體可以參考 Python 官方文檔中的格式化字符串部分:https://docs.python.org/3/library/string.html#format-string-syntax
丸趣 TV 網 – 提供最優質的資源集合!
正文完