【问题标题】:How to increment letters in Python?如何在 Python 中增加字母?
【发布时间】:2019-09-25 18:21:39
【问题描述】:

编写一个程序,输入一个字符(长度为 1 的字符串),你应该假设它是一个大写字符;输出应该是字母表中的下一个字符。如果输入是'Z',你的输出应该是'A'。 (您将需要使用 if 语句。) 到目前为止,我已经尝试了几个这样的代码:

chr = input()
if chr == '65':
        x = chr(ord(chr) + 1)
print(chr(65) + 1)

它说它打印时没有输出,只是不确定如何获得正确的输出。我对编程很陌生。

【问题讨论】:

    标签: python if-statement chr ord


    【解决方案1】:

    你可以使用以下思路:

    A = 65 Z = 90

    如果从输入中减去 ord('A'),则将范围缩小到 [0, 25]

    因此,您需要在 [0, 25] 范围内定义输出。为避免超出此范围,您应该使用 '%'。

    char_input = input()
    return chr((ord(char_input) - ord('A') + 1) % 26 + ord('A'))
    

    这意味着,给定输入,您将减去 ord('A') 的值以“修复”范围,然后加上 + 1。您将取 % 26 以避免超出范围。毕竟,再次添加 ord('A') 。

    【讨论】:

      【解决方案2】:

      这应该可行:

      my_chr = ord(input())
      if my_chr == 90:
              print('A')
      else:
          print(chr(my_chr+1))
      

      它接受输入字母 (A-Z) 并获取其 ord() 值。然后它检查该值是否等于Z (ord('Z') == 90) 并打印A 否则,它将其递增1,然后将其转回字符串并打印它。

      【讨论】:

        【解决方案3】:

        希望这就是你要找的东西

        _chr = input('Enter character(A-Z): ')
        if _chr == 'Z':
            print('A')
        else:
            print(chr(ord(_chr) + 1))
        

        【讨论】:

          【解决方案4】:
          alpha=input()
          if alpha =='Z': print('A')
          else:print(chr(ord(alpha)+1))
          

          "你需要使用 if 语句"

          【讨论】:

            【解决方案5】:

            下面的方法是使用 ascii_letters。

            import string
            
            // returns a string of all the alphabets
            // abcdefghijklmnopqrstuvwxyz"
            
               result = string.ascii_letters 
            
            // get the index of the input alphabet and return the next alphabet in the results string. 
            // using the modulus to make sure when 'Z' is given as the input it returns to the first alphabet. 
            
               result[(result.index(alphabet.lower()) + 1) % 26].upper() 
            

            【讨论】:

            • 所提供的答案被标记为低质量帖子以供审核。以下是How do I write a good answer? 的一些指南。提供的这个答案可能是正确的,但它可以从解释中受益。仅代码答案不被视为“好”答案。来自review
            • @MyNameIsCaleb 原因?
            • 提供的这个答案可能是正确的,但它可以从解释中受益。仅代码答案不被视为“好”答案为您的答案添加解释,并可能链接到您使用的函数/方法的文档(如果相关)。
            猜你喜欢
            • 2020-05-19
            • 2012-01-19
            • 1970-01-01
            • 1970-01-01
            • 2014-01-22
            • 2019-02-27
            • 1970-01-01
            • 1970-01-01
            • 2017-08-23
            相关资源
            最近更新 更多