python中怎么进行 Python 中的字符串格式化表达式,将字符串的值插入
时间: 2023-12-10 20:42:05 浏览: 36
Python 中的字符串格式化表达式可以使用 `%` 运算符来实现。具体用法如下:
1. 在字符串中使用占位符 `%s` 表示需要插入一个字符串,`%d` 表示需要插入一个整数,`%f` 表示需要插入一个浮点数,以此类推。
2. 在字符串末尾使用 `%` 运算符,后面紧跟着一个元组,元组中包含需要插入的值,按照顺序与占位符一一对应。
例如:
```python
name = "Tom"
age = 18
score = 98.5
# 使用字符串格式化表达式
print("My name is %s, I'm %d years old, and my score is %.1f." % (name, age, score))
```
输出结果为:
```
My name is Tom, I'm 18 years old, and my score is 98.5.
```
除了这种方法,Python 3.6 以后还支持一种新的格式化字符串方法,使用 f-string(也称为 formatted string literals)。使用 f-string,可以在字符串前添加 `f` 或 `F` 来创建一个格式化字符串,在字符串中使用 `{}` 表示需要插入一个变量的值。
例如:
```python
name = "Tom"
age = 18
score = 98.5
# 使用 f-string
print(f"My name is {name}, I'm {age} years old, and my score is {score:.1f}.")
```
输出结果为:
```
My name is Tom, I'm 18 years old, and my score is 98.5.
```