【问题标题】:Ordinal Number Error, Python 3序数错误,Python 3
【发布时间】:2016-08-05 12:07:37
【问题描述】:

我的 Python 代码有问题。我正在尝试显示用户输入的序号。因此,如果我输入 32,它将显示第 32 个,或者如果我输入 576,它将显示第 576 个。唯一不起作用的是 93,它显示第 93 位。每个其他数字都有效,我不知道为什么。这是我的代码:

num = input ('Enter a number: ')
end = ''
if num[len(num) - 2] != '1' or len(num) == 1:
  if num.endswith('1'):
    end = 'st'
  elif num.endswith('2'):
    end = 'nd'
  elif num == '3':
    end = 'rd'
  else:
    end = 'th'
else:
  end = 'th'
ornum = num + end
print (ornum)

【问题讨论】:

    标签: python-3.x ordinals


    【解决方案1】:

    您在 2 个地方使用 endswith(),而不是 3 个:

    if num.endswith('1'):
        end = 'st'
    elif num.endswith('2'):
        end = 'nd'
    #elif num == '3':  WRONG
    elif num.endswith('3'):
        end = 'rd'
    

    在您的代码中,它将测试“如果 num 等于 3”而不是“如果 num 以 3 结尾”。

    【讨论】:

      【解决方案2】:

      由于某种原因,当涉及到3 时,您忘记检查endswith()

      elif num.endswith('3'):
          end = 'rd'
      

      顺便说一句,您可以通过阅读 SE Code Review 上的 this question 来改进您的代码,其中包括这个很棒的版本:

      SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
      def ordinal(num):
          if 10 <= num % 100 <= 20:
              suffix = 'th'
          else:
              suffix = SUFFIXES.get(num % 10, 'th')
          return str(num) + suffix
      

      【讨论】:

        猜你喜欢
        • 2013-11-24
        • 2015-11-09
        • 2018-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-23
        • 2018-05-30
        • 2018-05-24
        相关资源
        最近更新 更多