在使用format()函數(shù)時(shí),以下是一些最佳實(shí)踐:
name = "Alice"
age = 30
# 使用位置參數(shù)
print("My name is {} and I am {} years old".format(name, age))
# 使用關(guān)鍵字參數(shù)
print("My name is {name} and I am {age} years old".format(name=name, age=age))
num = 10
# 格式化為整數(shù)
print("The number is {:d}".format(num))
name = "Alice"
try:
print("My name is {} and I am {} years old".format(name))
except IndexError:
print("Invalid number of arguments provided")
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old")
通過遵循這些最佳實(shí)踐,可以更有效地使用format()函數(shù)來格式化字符串。