如何从 Python 中的字符串中提取数字? [英] How to extract numbers from a string in Python?

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

问题描述

我会提取字符串中包含的所有数字.正则表达式或 isdigit() 方法哪个更适合此目的?

示例:

line = "hello 12 hi 89"

结果:

[12, 89]

解决方案

如果您只想提取正整数,请尝试以下操作:

<预><代码>>>>txt = h3110 23 猫 444.4 兔子 11 2 狗">>>[int(s) for s in txt.split() if s.isdigit()][23, 11, 2]

我认为这比 regex 示例更好,因为您不需要另一个模块,并且它更具可读性,因为您不需要解析(和学习)正则表达式迷你语言.

这不会识别浮点数、负整数或十六进制格式的整数.如果您不能接受这些限制,jmnas 下面的回答会成功的.

I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit() method?

Example:

line = "hello 12 hi 89"

Result:

[12, 89]

解决方案

If you only want to extract only positive integers, try the following:

>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]

I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.

This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.

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

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