【问题标题】:Assigning values to character A-Z in python [closed]在python中为字符A-Z赋值[关闭]
【发布时间】:2017-08-31 15:31:14
【问题描述】:

我是菜鸟。我正在尝试将值从 A 分配到 Z。 这很长。

   A= 97
   B= 98
   C= 99
   D= 100
   ...
   Z= 122

最好的方法是什么?

【问题讨论】:

  • 不要创建这样的变量。你为什么要这么做?
  • 您不需要分配。有ord('A'.lower())
  • 可以使用ord(str)函数
  • 一旦你有了这些变量,你打算用它们做什么?
  • @MosesKoledoye 为什么不直接使用ord('a')?为什么是lower()

标签: python ascii


【解决方案1】:

你可以这样做:

import string

alpha_dict = {k: ord(k) for k in string.ascii_lowercase}
print(alpha_dict)  # {'r': 114, 'l': 108, 'z': 122, ...}

并访问您的变量,例如alpha_dict['a']


请注意,您在示例中的值对应于 小写 字母,但您使用 大写 命名变量。如果你真的想要大写,而不是循环遍历ascii_lowercase 循环遍历ascii_uppercase

【讨论】:

    【解决方案2】:

    您可以使用ord('letter'),而不是对每个字母进行硬编码。例如,ord('a') 将返回数字 97,它代表 ASCII 中的字母 a

    编辑:

    我使用Ev. Kounis 的代码来制作字典,因为我的代码错了。有问题我可以删除。

    import string
    
    alpha_dict = {k: ord(k) for k in string.ascii_uppercase}
    
    '''Iterates in keys of alpha_dict, turning the key to lowercase, removes 
     the old key and replaces it with the new lowercase one'''
    for key in alpha_dict:
        lower = key.lower()
        alpha_dict[lower] = alpha_dict.pop(key)
    
    print(alpha_dict)
    

    【讨论】:

    • 抱歉,我的问题不清楚。我想将 'a' 的 ASCII 值放在 'A' 中。有什么办法吗?
    • @ShikhaNepal 检查我的编辑,我认为它满足您的需求。
    猜你喜欢
    • 2020-12-23
    • 2014-11-22
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    相关资源
    最近更新 更多