You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现大写字母与ASCII码带表头双列垂直输出问询

Python3.7 实现大写字母与对应字符编码两列垂直输出

问题背景

使用Python 3.7版本需要展示大写英文字母(A-Z)对应的字符编码,原有代码输出为横向排列,需要调整为两列垂直展示,顶部带有表头,每一行对应展示一个大写字母和它的字符编码。

原有代码

def uppercaseAlphabets():
    # uppercase
    for c in range(65, 91):
        print(chr(c), end=" ");

    print("");


# Function to print the alphabet upper case codes
def uppercaseCodes():
    for c in range(65, 91):
        print((c), end=" ");
    print("");


print("Uppercase Alphabets");
uppercaseAlphabets();

print("Uppercase Codes ");
uppercaseCodes();

原有输出

Uppercase Alphabet
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 
Uppercase Codes 
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 

期望输出

Uppercase Alphabet     Uppercase Codes
         A                    65
         B                    66
         C                    67
... 后续内容依次排列

调整方案

原有代码的问题是将字母和编码分为两次遍历分别输出,所以只能横向展示。修改为单次遍历同时输出对应字母和编码即可,借助Python字符串格式化能力可以快速实现对齐效果,完整修改后代码如下:

# 打印表头,设置两列宽度保证对齐
print(f"{'Uppercase Alphabet':<22}{'Uppercase Codes':<15}")
for c in range(65, 91):
    # 每轮循环输出一组对应字母和编码,^代表内容居中,数字为列宽度可自行调整
    print(f"{chr(c):^22}{c:^15}")

如果需要调整对齐方式,将格式化中的^替换为<即可实现左对齐,替换为>即可实现右对齐。

内容的提问来源于stack exchange,提问作者Ken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 07:27:04