python格式化输出格式
时间: 2023-10-11 15:11:55 浏览: 45
在 Python 中,格式化输出可以使用字符串的 format() 方法和 % 操作符。以下是一些常见的格式化输出格式:
使用 format() 方法:
1. {} 占位符:使用默认顺序,可以在 {} 中指定占位符的位置
```
print("My name is {}, I'm {} years old".format("John", 25))
# 输出:My name is John, I'm 25 years old
print("My name is {1}, I'm {0} years old".format(25, "John"))
# 输出:My name is John, I'm 25 years old
```
2. 格式化限定符:可以格式化输出数字、浮点数、科学计数法等
```
print("My age is {:.2f}".format(25.123))
# 输出:My age is 25.12
print("My salary is {:,}".format(123456789))
# 输出:My salary is 123,456,789
```
使用 % 操作符:
1. %s 占位符:用于字符串
```
print("My name is %s" % "John")
# 输出:My name is John
```
2. %d 占位符:用于整数
```
print("My age is %d" % 25)
# 输出:My age is 25
```
3. %f 占位符:用于浮点数
```
print("My salary is %.2f" % 1234.5678)
# 输出:My salary is 1234.57
```
4. %e 占位符:用于科学计数法
```
print("The speed of light is %e m/s" % 299792458)
# 输出:The speed of light is 2.997925e+08 m/s
```