Py学习  »  Python

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

Steve • 6 年前 • 1727 次点击  

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

 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
 
1727 次点击  
文章 [ 5 ]  |  最新文章 6 年前