在 Python 中从字符串中提取数字 [英] Extract Number from String in Python

查看:80
本文介绍了在 Python 中从字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的新手,我有一个字符串,我想从字符串中提取数字.例如:

str1 = "3158 条评论"打印 (re.findall('\d+', str1 ))

输出为 ['4', '3']

我只想获得 3158,最好是整数,而不是列表.

解决方案

您可以使用 str.isdigit 方法通过 digitsfilter 字符串,

<预><代码>>>>int(过滤器(str.isdigit,str1))3158

I am new to Python and I have a String, I want to extract the numbers from the string. For example:

str1 = "3158 reviews"
print (re.findall('\d+', str1 ))

Output is ['4', '3']

I want to get 3158 only, as an Integer preferably, not as List.

解决方案

You can filter the string by digits using str.isdigit method,

>>> int(filter(str.isdigit, str1))
3158

这篇关于在 Python 中从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆