在 Python 中,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."
指定变量值的位置和顺序:
item1 = "apple"
item2 = "banana"
item3 = "orange"
message = "{}, {}, and {} are fruits.".format(item1, item2, item3)
print(message) # 输出:"apple, banana, and orange are fruits."
设置变量值的格式:
pi = 3.14159
message = "The value of pi is approximately {:.2f}.".format(pi)
print(message) # 输出:"The value of pi is approximately 3.14."
使用命名参数进行格式化:
person = {"name": "Bob", "age": 30}
message = "My name is {name} and I am {age} years old.".format(**person)
print(message) # 输出:"My name is Bob and I am 30 years old."
根据索引或键访问变量值:
fruits = ["apple", "banana", "orange"]
message = "I like {0}, {1}, and {2}.".format(fruits[0], fruits[1], fruits[2])
print(message) # 输出:"I like apple, banana, and orange."
format()
方法提供了一种灵活的方式来格式化字符串,并在其中插入变量值、数字和其他数据类型。它支持多种格式设置选项,如填充字符、对齐方式、小数位数等,可以根据具体需求进行定制。 format()
方法常用于打印输出、生成动态文本、日志记录等场景