Py学习  »  Python

使用单行筛选字符串python中的数字

Steve • 6 年前 • 1682 次点击  

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

 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() ]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/35272
 
1682 次点击  
文章 [ 5 ]  |  最新文章 6 年前
PrakashG Musty450
Reply   •   1 楼
PrakashG Musty450    6 年前

在我看来,lambda表达式中有一个小错误。
尝试:

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

当然 newString 现在是一个列表,但我希望这能回答您最初的问题。

Stan S.
Reply   •   2 楼
Stan S.    6 年前

比如:

newstring = ''.join(map(lambda x: x if not x.isdigit() else "", string.split() ))

与空格完全相同:

newstring = ' '.join(map(lambda x: x if not x.isdigit() else "", string.split() )).replace('  ', ' ')
Piotr Kamoda
Reply   •   3 楼
Piotr Kamoda    6 年前

在代码中,您正在比较 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 从你的代码,应该是好的。

Meet Maheshwari
Reply   •   4 楼
Meet Maheshwari    6 年前

newString = " ".join([x for x in string.split() if x.isdigit() == False])

所有东西只在一行代码中。

Adam.Er8
Reply   •   5 楼
Adam.Er8    6 年前

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

is is an identity comparison operator

is not x is y x is not y

token token.isdigit()