python数据格式化
时间: 2023-08-08 14:09:16 浏览: 49
Python中有多种数据格式化的方法,其中比较常用的有以下三种:
1. 使用 % 运算符进行格式化:
例如,将一个字符串和一个整数格式化输出:
```
name = "Alice"
age = 20
print("My name is %s and I am %d years old." % (name, age))
```
输出结果为:
```
My name is Alice and I am 20 years old.
```
2. 使用 str.format() 方法进行格式化:
例如,将一个字符串和一个浮点数格式化输出:
```
name = "Bob"
height = 1.80
print("My name is {} and I am {:.2f} meters tall.".format(name, height))
```
输出结果为:
```
My name is Bob and I am 1.80 meters tall.
```
3. 使用 f-string 进行格式化:
从 Python 3.6 开始,可以使用 f-string 进行格式化,它的语法比较简单,只需要在字符串前加上 f,然后在字符串中使用花括号 {} 表示需要格式化的变量或表达式即可。
例如,将一个字符串和一个布尔值格式化输出:
```
name = "Charlie"
is_student = True
print(f"My name is {name} and I am {'a student' if is_student else 'not a student'}.")
```
输出结果为:
```
My name is Charlie and I am a student.
```