isdigit不适合我

时间:2015-10-23 15:10:41

标签: python python-2.7

def listMaker(a, b):
    if b.isdigit() == False:
         print("Sorry is not a valid input")
    else:
         newList = [a] * b
         return newList

我收到错误:

AttributeError: 'int' object has no attribute 'isdigit'

我该如何解决这个问题?

5 个答案:

答案 0 :(得分:3)

isdigit()str类的方法。根据尝试实现的目标,首先将b转换为字符串:

if not str(b).isdigit()

或(和更好),使用isinstance检查属性类型:

if not isinstance(b, int)

答案 1 :(得分:1)

您可以将输入包装在int中。

def listMaker(a, b):
    try:
        b = int(b)
    except ValueError:
         print("Sorry is not a valid input")
    else:
         newList = [a] * b
         return newList

示例:

>>> listMaker(1, '4')
[1, 1, 1, 1]
>>> listMaker(1, 'josh')
Sorry is not a valid input
>>> listMaker(1, '4.2')
Sorry is not a valid input

这将是pythonic EAFP

答案 2 :(得分:0)

似乎只有string类型有此方法,而不是int。请参阅there

答案 3 :(得分:0)

似乎你已经有了整数,如果不确定你能做到:

if isinstance(b, int):
    print("Sorry is not a valid input")

答案 4 :(得分:0)

文档字符串

S.isdigit() -> bool

如果 S中的所有字符均为数字 ,则返回True,S中至少有一个字符,否则返回False。

让我们在python shell中尝试一下。

>>> aaa = '123'
>>> aaa.isdigit()
True

>>> bbb = '123a4'
>>> bbb.isdigit()
False

>>> ccc = 123
>>> ccc.isdigit()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'

我们还可以将 dir(aaa) dir(bbb) dir(ccc)进行比较。

相关问题