共計 813 個字符,預計需要花費 3 分鐘才能閱讀完成。
Python 中的 format 方法可以用于格式化字符串。它可以通過在字符串中插入占位符 {},然后使用 format 方法來填充這些占位符。
format 方法的基本語法如下:
string.format(value1, value2, ...)
其中,string 是要格式化的字符串,value1, value2, …是要插入的值。
以下是一些常見的用法示例:
- 簡單用法:
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.
- 指定順序:
name = "Alice"
age = 25
print("My name is {0} and I am {1} years old.".format(name, age))
輸出:My name is Alice and I am 25 years old.
- 命名參數:
name = "Alice"
age = 25
print("My name is {name} and I am {age} years old.".format(name=name, age=age))
輸出:My name is Alice and I am 25 years old.
- 格式化數字:
num = 3.1415926
print("The value of pi is {:.2f}".format(num))
輸出:The value of pi is 3.14
- 格式化日期和時間:
import datetime
now = datetime.datetime.now()
print("Current date and time is {:%Y-%m-%d %H:%M:%S}".format(now))
輸出:Current date and time is 2022-05-10 15:30:00
這只是 format 方法的一些簡單用法,還有其他更高級的用法,比如對齊,填充等,可以根據需要進一步研究。
丸趣 TV 網 – 提供最優質的資源集合!
正文完