控制台操作
2024/10/31原创大约 1 分钟约 430 字
1. 打印顶部标题
# 顶部标题
top_title = "People Information"
# 打印顶部标题
print(top_title)
print("=" * len(top_title)) # 可选:打印一行分隔线
2. 控制台打印表格
from prettytable import PrettyTable
# 创建一个 PrettyTable 对象
table = PrettyTable()
# 添加表格列
table.set_header_row(['Header 1', 'Header 2'])
# 添加列(但不设置 field_names,这样就没有表头)
# 注意:这里我们直接添加行数据,而不设置列名
table.add_row(["Alice", 24])
table.add_row(["Bob", 30])
table.add_row(["Charlie", 22])
# 打印表格,不包括表头
print(table)
3. 控制台打印表格不包括表头
from tabulate import tabulate
data = [
["Alice", 24],
["Bob", 30],
["Charlie", 22]
]
# 打印表格,不包括表头
print(tabulate(data, tablefmt="grid"))
## 第一行作为表头打印
print(tabulate(data, headers="firstrow", tablefmt="grid"))
4. 控制台输出菜单
from tabulate import tabulate
data = [
["Alice", 25, "Engineer"],
["Bob", 30, "Designer"]
]
# 手动构造表头,让前两列看起来像是被一个大标题覆盖
headers = ["", "Personal Info", "Personal Info", "Role"] # 注意第一个是空
# 但数据行需要对齐
table_data = [
["Name", "Age", "Role"], # 这是真正的表头
["Alice", 25, "Engineer"],
["Bob", 30, "Designer"]
]
def handle_choice(choice):
if choice == '1':
print("👉 正在查看数据...")
elif choice == '2':
print("➕ 请输入新数据:")
data = input("> ")
print("➕ 请输入日期:")
start = input("> ")
print(f"已添加:{data,start}")
elif choice == '3':
print("🗑️ 删除数据功能暂未实现")
elif choice == '4':
print("👋 再见!")
return False # 退出循环
else:
print("❌ 无效选项,请重新输入!")
return True # 继续循环
# 使用 'plain' 格式并手动添加合并的标题
running = True
while running:
print(" Personal Info")
print(tabulate(table_data, headers="firstrow", tablefmt="grid"))
print("| Designer |")
print("+--------+-------+----------+")
choice = input("请选择功能 (1-4): ").strip()
running = handle_choice(choice)