私信  •  关注

Piotr Kamoda

Piotr Kamoda 最近创建的主题
Piotr Kamoda 最近回复了
7 年前
回复了 Piotr Kamoda 创建的主题 » 使用单行筛选字符串python中的数字

在代码中,您正在比较 token 和 token.isdigit() 具有 is not 操作员。如果对象是同一个对象,它会比较这些对象,但是 string 和 boolean 甚至不是同一类型,所以结果总是正确的:

>>> string = "these 5 sentences should not have 2 numbers in them"
>>> string.split()
['these', '5', 'sentences', 'should', 'not', 'have', '2', 'numbers', 'in', 'them']
>>> token = string.split()[3]
>>> token
'should'
>>> token.isdigit()
False
>>> token is not token.isdigit()
True
>>> token = string.split()[1]
>>> token
'5'
>>> token is not token.isdigit()
True

所以你应该直接下车 token is 从你的代码,应该是好的。