方法1:
# 创建字典
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# 使用字典键作为占位符
template = "My name is {name} and I live in {city}. I am {age} years old."
# 使用format方法和字典来填充占位符
formatted_string = template.format(**person)
print(formatted_string)
# 输出: My name is Alice and I live in New York. I am 30 years old.
方法2:
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# 使用f-string和字典
formatted_string = f"My name is {person['name']} and I live in {person['city']}. I am {person['age']} years old."
print(formatted_string)
# 输出: My name is Alice and I live in New York. I am 30 years old.