为什么不,if,elif或者在Python中使用.lower()?

时间:2015-01-28 20:46:49

标签: python if-statement python-3.x lowercase

程序需要接受并匹配单词的任何大小写版本,这就是使用.lower()的原因。运行此选项并输入“January”时,将打印else行而不是if行。

month = input("\nPlease enter the month\n")
if month.lower == ("january"):
    month = int(1)
    print(month)
elif month.lower == ("february"):
    month = int(2)
    print(month)
elif month.lower == ("march"):
    month = int(3)
    print(month) #etc.
else:
    print("That is not a month\n")

1 个答案:

答案 0 :(得分:12)

您需要调用方法:

month.lower() == 'march'

该方法也是一个对象,如果不调用它,则将该方法与字符串进行比较。他们永远不会平等:

>>> month = 'January'
>>> month.lower
<built-in method lower of str object at 0x100760c30>
>>> month.lower == 'January'
False
>>> month.lower == 'january'
False
>>> month.lower() == 'january'
True