python排版输入输出
时间: 2023-09-05 16:14:31 浏览: 78
在Python中,可以使用不同的方法对输入和输出进行排版。
1. 格式化字符串输出:
使用格式化字符串,可以将变量的值插入到字符串中。常见的方式是使用百分号(%)或者使用字符串的`format()`方法。
使用百分号(%)进行格式化:
```python
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
```
使用`format()`方法进行格式化:
```python
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
```
2. f-string格式化:
从Python 3.6开始,引入了f-string(格式化字符串字面值)语法,它提供了一种更简洁和直观的方式来格式化输出。
```python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
```
3. 对齐和填充:
可以使用一些方法对输出进行对齐和填充,例如使用`ljust()`, `rjust()`, `center()`等方法。
```python
name = "Alice"
print(name.ljust(10)) # 左对齐
print(name.rjust(10)) # 右对齐
print(name.center(10)) # 居中对齐
```
4. 使用制表符:
在输出中使用制表符`\t`可以实现列对齐的效果。
```python
print("Name\tAge")
print("Alice\t25")
print("Bob\t30")
```
这些是一些常见的方法来排版Python的输入和输出。根据具体的需求,可以选择适合的方法进行排版。