python 字符串格式化
时间: 2023-07-24 07:38:24 浏览: 90
在Python中,字符串格式化可以让我们将变量插入到字符串中,以便在输出时将变量的值包含在字符串中。Python提供了多种字符串格式化的方式,下面列举了其中的几种:
1. 使用占位符
使用占位符是最常见的字符串格式化方式。在字符串中使用占位符(如`%d`、`%f`、`%s`等),然后使用`%`运算符将变量的值插入到占位符中。例如:
``` python
name = "Tom"
age = 20
print("My name is %s, and I am %d years old." % (name, age))
```
输出结果为:
```
My name is Tom, and I am 20 years old.
```
在上面的代码中,`%s`表示插入一个字符串变量,`%d`表示插入一个整数变量。多个变量的值使用一个元组传递给`%`运算符。
2. 使用format()函数
`format()`函数也是一种常见的字符串格式化方式。在字符串中使用大括号`{}`作为占位符,然后使用`format()`函数将变量的值插入到占位符中。例如:
``` python
name = "Tom"
age = 20
print("My name is {}, and I am {} years old.".format(name, age))
```
输出结果为:
```
My name is Tom, and I am 20 years old.
```
在上面的代码中,大括号中不需要指定变量类型,`format()`函数会自动根据变量的类型进行格式化。
3. 使用f-string
在Python 3.6及以上版本中,还可以使用f-string进行字符串格式化。f-string以`f`开头,使用大括号`{}`作为占位符,并在大括号中使用变量名。例如:
``` python
name = "Tom"
age = 20
print(f"My name is {name}, and I am {age} years old.")
```
输出结果为:
```
My name is Tom, and I am 20 years old.
```
在上面的代码中,大括号中直接使用变量名,无需使用`%`运算符或`format()`函数。
除了上面介绍的几种方式,Python还提供了其他一些字符串格式化的方式,如使用模板字符串、使用字符串拼接等。可以根据具体的情况选择合适的方式进行字符串格式化。
阅读全文