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方法的一些簡單用法,還有其他更高級的用法,比如對齊,填充等,可以根據需要進一步研究。