`format`语句是Python中用于格式化字符串的一种方法,它使用花括号 `{}` 作为占位符,并通过 `format()` 函数将实际的值填入这些占位符中。以下是 `format` 语句的基本用法和一些高级用法:
基本用法
按位置传参
```python
name = "小明"
age = 18
print("我叫{},今年{}岁".format(name, age))
输出: 我叫小明,今年18岁
```
按索引指定参数
```python
msg = "{1}买了{0}个苹果".format("三","小红")
print(msg)
输出: 小红买了三个苹果
```
重复使用同一个值
```python
text = "{0}喜欢吃{1}, {0}也喜欢喝{2}".format("我","面条","可乐")
print(text)
输出: 我喜欢吃面条, 我也喜欢喝可乐
```
高级用法
对齐和填充
```python
左对齐,右对齐,居中对齐
print("{:<10}".format("hello")) 输出: hello(左对齐,宽度为10)
print("{:^10}".format("hello")) 输出: hello (居中对齐,宽度为10)
print("{:*^10}".format("hello")) 输出: *hello* (居中对齐,宽度为10,用*填充)
填充字符
print("{:0>10}".format("hello")) 输出: 00000hello(右对齐,宽度为10,用0填充)
```
格式化数字
```python
number = 3.1415926
print("The value of pi is {:.2f}".format(number))
输出: The value of pi is 3.14
```
关键字(key)填充
```python
a = 'hello {name}, welcome to {skill}'
print(a.format(name='lsg', skill='python'))
输出: hello lsg, welcome to python
lsgPy = {'name':'lsg','skill':'python'}
a = 'hello {key[name]}, welcome to {key[skill]}'
print(a.format(lsgPy))
输出: hello lsg, welcome to python
```
f-string(Python 3.6+)
f-string 是一种更简洁的格式化字符串的方法,直接在字符串前加 `f` 或 `F`,然后在花括号里写变量名即可。
```python
name = "小张"
age = 22
score = 95.5
print(f"我叫{name},考了{score}分")
输出: 我叫小张,考了95.5分
```
f-string 支持表达式和函数调用:
```python
print(f"再过两年我{age + 2}岁")
输出: 再过两年我24岁
print(f"我的成绩是{score:.1f}")
输出: 我的成绩是95.5分
```
总结
`format` 语句提供了灵活的字符串格式化功能,可以通过位置、索引、关键字等方式将变量插入到字符串中,并且支持对齐、填充和格式化数字等高级功能。f-string 则是 Python 3.6 引入的一种更简洁的格式化方法,通过在字符串前加 `f` 并在花括号里写变量名来实现格式化。根据具体需求和代码可读性选择合适的格式化方法。