python3提取字符串中的数字_如何在Python中从字符串中提取数字?

本文介绍了如何在Python3中从字符串中提取数字,包括正整数、浮点数和负数。示例代码展示了使用列表推导式、正则表达式等方法,以及处理各种数字格式的技巧。
摘要由CSDN通过智能技术生成

14 回复 | 直到 1 年前

a007be5a61f6aa8f3e85ae2fc18dd66e?s=32&d=identicon&r=PG

1

430

3 年前

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

>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"

>>> [int(s) for s in str.split() if s.isdigit()]

[23, 11, 2]

我认为这比regex示例好有三个原因。首先,您不需要另一个模块;其次,它更可读,因为您不需要解析regex mini语言;第三,它更快(因此可能更像是pythonic):

python -m timeit -s "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "[s for s in str.split() if s.isdigit()]"

100 loops, best of 3: 2.84 msec per loop

python -m timeit -s "import re" "str = 'h3110 23 cat 444.4 rabbit 11 2 dog' * 1000" "re.findall('\\b\\d+\\b', str)"

100 loops, best of 3: 5.66 msec per loop

这将无法识别浮点数、负整数或十六进制格式的整数。如果你不能接受这些限制,

slim's answer below

会成功的。

favicon.png

2

404

4 年前

我会用regexp:

>>> import re

>>> re.findall(r'\d+', 'hello 42 I\'m a 32 string 30')

['42', '32', '30']

这也将匹配来自

bla42bla

. 如果只希望数字由单词边界(空格、句点、逗号)分隔,则可以使用\b:

>>> re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')

['42', '32', '30']

以数字列表而不是字符串列表结束:

>>> [int(s) for s in re.findall(r'\b\d+\b', 'he33llo 42 I\'m a 32 string 30')]

[42, 32, 30]

14663c07f99bd2fdc191b05db9d3e900?s=32&d=identicon&r=PG&f=1

3

81

2 年前

这已经有点晚了,但是您也可以扩展regex表达式来解释科学符号。

import re

# Format is [(, ), ...]

ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",

['-12.34', 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值