Python.IS Digit应该检查多个数字

  • 本文关键字:数字 IS Digit Python python
  • 更新时间 :
  • 英文 :


我在python上编写小程序只是为了了解splitisdigit函数如何工作

程序是:

s = input('type something:')
if s.isdigit():
    a = s.split()
    a = list(map(int, a))
    print('What you typed was number and it was converted to integer')
    print('Result is:', a)
else:
    a = s.split()
    print('What you typed was words it was not converted to integer')
    print('Result is:', a)

问题是什么...当我键入一个单个数字程序时,效果很好。isdigit检查数字。(真正包含数字的列表(。

当我打字4(只有一个数字 - 很好(

但是当我键入3 6 4 2 6 3 3个多数isdigit无法检查

为什么?

正如所有评论已经说的:空白不是数字,因此字符串" 3 6 4 2 6 3"将返回false。

>>> print("3 6 4 2 6 3".isdigit())
False

您可以使用替换((函数剥离所有空间:

>>> print("3 6 4 2 6 3".replace(" ", "").isdigit())
True

这是因为 sstring type

的变量

如果要检查字符串s的每个符号,是否应该尝试使用[x.isdigit() for x in a]

相关内容

最新更新