Skip to main content
 首页 » 编程设计

python之使用单行从字符串python中过滤掉数字

2025年05月04日36soundcode

我正在重构我的代码,以便它以更 Pythonic 的方式完成。具体来说我有一个部分 如果该标记不是整数,则从字符串返回标记。最初我写的函数如下

 string = "these 5 sentences should not have 2 numbers in them" 
 newString = [] 
 for token in string.split(): 
     if token.isdigit() == False: 
         newString.append(token) 
 newString = " ".join(newString) 
 print(newString) 

虽然这行得通,但我不会让代码看起来不那么笨拙。于是我改写如下

   newString = [token for token in string.split() if token is not  
   token.isdigit() ] 

但这似乎并没有捕捉到数字。为什么 lambda 表达式不起作用?

请您参考如下方法:

试试这个:

string = "these 5 sentences should not have 2 numbers in them" 
 
newString = " ".join(token for token in string.split() if not token.isdigit()) 
 
print(newString) 

问题是 is 的使用。

虽然 python 有时与英语非常相似,这很好,但在某些情况下它会造成混淆 :)

is is an identity comparison operator ,

引用文档:

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value.

它试图查看 token(这是一些字符串)是否不是 token.isdigit()(这是一些 bool 值),这当然对所有人都是正确的代币 :)