我在python上编写小程序只是为了了解split
和isdigit
函数如何工作
程序是:
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
这是因为 s
是 string
type
如果要检查字符串s
的每个符号,是否应该尝试使用[x.isdigit() for x in a]
。