Python中的`format`函数用于格式化字符串,它允许你将变量或表达式插入到字符串中的指定位置。以下是`format`函数的基本用法:
基本用法
顺序替换
使用位置索引来指定参数的顺序。
```python
name = "Alice"
age = 25
text = "My name is {} and I am {} years old."
print(text.format(name, age)) 输出:My name is Alice and I am 25 years old.
根据索引替换
使用花括号`{}`和冒号`:`来指定参数的位置。
```python
name = "Alice"
age = 25
text = "My name is {0} and I am {1} years old."
print(text.format(name, age)) 输出:My name is Alice and I am 25 years old.
根据关键字替换
使用关键字参数来指定参数的顺序,这样可以不依赖于参数的位置。
```python
name = "Alice"
age = 25
text = "My name is {name} and I am {age} years old."
print(text.format(name=name, age=age)) 输出:My name is Alice and I am 25 years old.
进阶用法
格式化数字
可以指定小数点位数、百分比格式等。
```python
pi = 3.
print("The value of pi is {:.2f}".format(pi)) 输出:The value of pi is 3.14
rate = 0.85
print("Pass rate is {:.1%}".format(rate)) 输出:Pass rate is 85.0%
文本对齐与填充
可以控制文本的对齐方式和填充字符。
```python
name = "Alice"
age = 25
text = "My name is {:<10} and I am {:>5} years old."
print(text.format(name, age)) 输出:My name is Alice and I am25 years old.
总结
`format`函数是Python中非常灵活和强大的字符串格式化工具,适用于各种场景,包括简单的占位符替换、复杂的嵌套操作、数字格式化和自定义样式等。它增强了代码的可读性和可维护性