Python的format()函數是用來格式化字符串的方法。它可以在字符串中插入變量、常量或表達式,并指定它們的格式。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.
print("My name is {0} and I am {1} years old.".format(name, age))
輸出:My name is Alice and I am 25 years old.
print("My name is {name} and I am {age} years old.".format(name="Bob", age=30))
輸出:My name is Bob and I am 30 years old.
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
輸出:The value of pi is 3.14
print("My name is {0:10} and I am {1:03d} years old.".format("Alice", 5))
輸出:My name is Alice and I am 005 years old.
format()函數可以根據數據類型自動選擇格式化選項,如浮點數的精度、整數的進制等。使用format()函數可以實現復雜的字符串格式化需求,并提高代碼的可讀性。