python格式化输出
时间: 2023-05-31 07:05:35 浏览: 68
Python中的格式化输出可以使用字符串的format()方法和%操作符两种方式来实现。
使用字符串的format()方法:
1. 基本用法:
```python
name = 'Alice'
age = 20
print('My name is {}, and I am {} years old.'.format(name, age))
```
输出结果为:
```
My name is Alice, and I am 20 years old.
```
2. 格式控制:
- 格式化整数:{:d}
```python
num = 123
print('The number is {:d}'.format(num))
```
输出结果为:
```
The number is 123
```
- 格式化浮点数:{:f}
```python
pi = 3.1415926
print('The value of pi is {:.2f}'.format(pi))
```
输出结果为:
```
The value of pi is 3.14
```
- 格式化字符串:{:s}
```python
message = 'Hello, {}!'
name = 'Bob'
print(message.format(name))
```
输出结果为:
```
Hello, Bob!
```
- 格式化十六进制数:{:x}
```python
num = 255
print('The hexadecimal representation of {} is {:x}'.format(num, num))
```
输出结果为:
```
The hexadecimal representation of 255 is ff
```
使用%操作符:
1. 基本用法:
```python
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. 格式控制:
- 格式化整数:%d
```python
num = 123
print('The number is %d' % num)
```
输出结果为:
```
The number is 123
```
- 格式化浮点数:%f
```python
pi = 3.1415926
print('The value of pi is %.2f' % pi)
```
输出结果为:
```
The value of pi is 3.14
```
- 格式化字符串:%s
```python
message = 'Hello, %s!'
name = 'Bob'
print(message % name)
```
输出结果为:
```
Hello, Bob!
```
- 格式化十六进制数:%x
```python
num = 255
print('The hexadecimal representation of %d is %x' % (num, num))
```
输出结果为:
```
The hexadecimal representation of 255 is ff
```
注意:使用%操作符格式化字符串时,格式控制符和变量之间要用%连接。而使用format()方法时,格式控制符和变量之间要用{}连接。