在Python中, .format() 是一种字符串格式化方法,用于创建动态的字符串。它允许将变量、表达式或其他值插入到一个字符串中的占位符位置。
下面土嘎嘎小编分享 .format() 方法的常见用法示例:
1. 基本使用:
〓〓python代码如下:〓〓
name = "Alice"
age = 25
message = "My name is {} and I'm {} years old.".format(name, age)
print(message)
输出:
My name is Alice and I'm 25 years old.
2. 通过索引指定顺序:
〓〓python代码如下:〓〓
name = "Bob"
age = 30
message = "My name is {1} and I'm {0} years old.".format(age, name)
print(message)
输出:
My name is Bob and I'm 30 years old.
3. 格式化数字:
〓〓python代码如下:〓〓
price = 19.99
quantity = 3
total = price * quantity
message = "The total cost is {:.2f}".format(total)
print(message)
输出:
The total cost is 59.97
在这个示例中, {:.2f} 表示浮点数格式化,保留两位小数。
4. 使用关键字参数:
〓〓python代码如下:〓〓
name = "Charlie"
age = 35
message = "My name is {name} and I'm {age} years old.".format(name=name, age=age)
print(message)
输出:
My name is Charlie and I'm 35 years old.
5. 使用字典和对象属性:
〓〓python代码如下:〓〓
person = {"name": "Dave", "age": 42}
message = "My name is {person[name]} and I'm {person[age]} years old.".format(person=person)
print(message)
输出:
My name is Dave and I'm 42 years old.
.format() 方法提供了强大的字符串格式化功能,可以根据需要进行更复杂的操作。详细的语法和用法,请参考Python官方文档或相关的Python教程和参考资料。