文章目錄
- 前言
- 1、位置參數
- 2、索引參數
- 3、命名參數
- 3、格式化參數
前言
??format() 是 Python 字符串對象的方法,用于將值插入到格式化字符串的占位符中。它是一種靈活和強大的字符串格式化工具。format() 方法可以在字符串中使用占位符 {},并通過傳遞參數將值插入到占位符的位置。占位符可以使用索引或命名來指定要插入的參數。
以下是 format() 方法的一些常見用法:
1、位置參數
message = "My name is {} and I am {} years old.".format(name, age)
2、索引參數
message = "My name is {0} and I am {1} years old.".format(name, age)
3、命名參數
message = "My name is {name} and I am {age} years old.".format(name=name, age=age)
3、格式化參數
pi = 3.14159
formatted_pi = "{:.2f}".format(pi) # 保留兩位小數