如何转换类的实例" filter"直接str

时间:2017-04-11 08:02:00

标签: python python-3.x

url = 'https://www.shanbay.com/read/article/97936/' 
temp = filter(str.isdigit,url)    #slect numbers

我可以直接将for...in expression转换为temp,而不是使用str吗?

3 个答案:

答案 0 :(得分:1)

filter返回一个迭代器,因此您必须加入其元素。

url = 'https://www.shanbay.com/read/article/97936/' 
temp = "".join(filter(str.isdigit,url))

答案 1 :(得分:1)

filter在Python 3中很懒,你需要将它们提供给一个消耗它们的函数并强制它们生成它们的元素。

url = 'https://www.shanbay.com/read/article/97936/' 
temp = filter(str.isdigit,url)  # filter object

如果将其提供给另一个使用它的函数,则可以取回元素。如果您需要一个字符串,只需join

nums = "".join(temp)

"".join将获取filter个实例中的所有元素,并将它们连接到生成""的空字符串97936;如果您需要int结果,请在int来电中使用。

答案 2 :(得分:0)

re.findall()怎么样?

import re
url = 'https://www.shanbay.com/read/article/97936/'
temp = re.findall('[0-9]+', url)