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方法的一些简单用法,还有其他更高级的用法,比如对齐,填充等,可以根据需要进一步研究。