共計 703 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 format()方法來格式化字符串。format()方法的基本語法是在字符串中使用占位符 {},然后調用 format() 方法,并將要替換的值作為參數(shù)傳遞給 format()方法。
以下是一些使用 format()方法的示例:
- 基本用法:
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
輸出:
My name is Alice and I am 25 years old.
- 指定參數(shù)位置:
name = "Alice"
age = 25
message = "My name is {0} and I am {1} years old.".format(name, age)
print(message)
輸出:
My name is Alice and I am 25 years old.
- 使用關鍵字參數(shù):
name = "Alice"
age = 25
message = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(message)
輸出:
My name is Alice and I am 25 years old.
- 格式化數(shù)字:
num = 3.1415926
formatted_num = "{:.2f}".format(num)
print(formatted_num)
輸出:
3.14
這些只是 format()方法的一些基本用法示例,實際上還有很多其他用法,比如格式化日期、填充字符串、指定對齊方式等等。你可以根據(jù)自己的需求進一步了解 format()方法的更多用法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質的資源集合!
正文完