python - 如何将类 "filter"的实例直接转换为 str

标签 python python-3.x

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

我可以直接将 temp 转换为 str,而不是使用 for...in 表达式

最佳答案

filters 在 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 调用中使用它。

关于python - 如何将类 "filter"的实例直接转换为 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43340058/

相关文章:

python - Django 简单历史 - save_without_historical_record() 对我不起作用

python - Pandas 左外连接多个列上的多个数据框

python - urllib/urllib2 返回的错误码和实际页面

Python 3 中心三角形

python - PyQt 本地化 : Translating a text through QPushButton w/use of . po 文件

python - 在不丢失数据的情况下停止 python 脚本

python - SQLAlchemy 使用路由查询错误的表

python - 如何使用 ElementTree 从深度嵌套的 XML 子元素中提取属性?

Python 静态类型不起作用

python - __new__() 不返回类实例时的继承