在Python中,格式化输出可以通过多种方式实现,包括使用字符串的`ljust()`, `rjust()`, `center()`方法,以及`format()`方法和第三方库`tabulate`。下面是一些示例代码,演示如何对齐输出:
使用字符串方法
```python
text = "Python"
print(text.ljust(10)) 左对齐输出,宽度为10
print(text.rjust(10)) 右对齐输出,宽度为10
print(text.center(10)) 居中对齐输出,宽度为10
使用`format()`方法
```python
name = "Alice"
age = 25
print("{:10} {:>5}".format(name, age)) 左对齐name,右对齐age
使用`tabulate`库
```python
from tabulate import tabulate
data = [["Alice", 25], ["Bob", 30], ["Charlie", 35]]
print(tabulate(data, tablefmt="grid")) 表格形式输出
对齐多个变量
```python
name = "Alice"
age = 25
print("{:<10} {:>5}".format(name, age)) 左对齐name,右对齐age
对齐表格数据
```python
from tabulate import tabulate
tableData = [["apples", "oranges", "cherries", "banana"],
["Alice", "Bob", "Carol", "David"],
["dogs", "cats", "moose", "goose"]]
def printTable(tableData):
colWidths = [max(len(str(cell)) for cell in col) for col in zip(*tableData)]
for row in tableData:
print("| " + " | ".join(str(cell).ljust(width + 2) for cell, width in zip(row, colWidths)) + " |")
printTable(tableData)
对齐输出中的数字和小数
```python
value = 3.14159
print("{:10.3f}".format(value)) 数字输出,宽度为10,保留3位小数
对齐输出中的字符串和数字
```python
name = "Alice"
age = 25
print("{:<10} {:>5}".format(name, age)) 左对齐name,右对齐age
对齐输出中的字符串,使用`f-string`
```python
name = "Alice"
age = 25
print(f"{name:<10} {age:>5}") 左对齐name,右对齐age
以上示例展示了如何使用Python进行格式化输出,包括左对齐、右对齐、居中对齐以及表格形式输出。您可以根据需要选择合适的方法进行格式化