从Python中的字符串中仅获取数字

问题描述 投票:0回答:9

我只想从字符串中获取数字。例如我有这样的东西

just='Standard Price:20000'

我只想打印出来

20000

所以我可以将它乘以任何数字。

我试过了

just='Standard Price:20000'
just[0][1:]

我得到了

 ''

解决这个问题的最佳方法是什么?我是菜鸟。

python
9个回答
39
投票

您可以使用正则表达式:

import re
just = 'Standard Price:20000'
price = re.findall("\d+", just)[0]

price = just.split(":")[1]

19
投票

您也可以尝试:

int(''.join(i for i in just if i.isdigit()))

8
投票

如果你想让它更简单,避免使用正则表达式,你还可以尝试Python的内置函数

filter
str.isdigit
函数来获取数字字符串并将返回的字符串转换为整数。这对于浮点数不起作用,因为小数字符被
str.isdigit
过滤掉。

Python 内置函数过滤器

Python 内置类型 str.isdigit

考虑问题中的相同代码:

>>> just='Standard Price:20000'
>>> price = int(filter(str.isdigit, just))
>>> price
20000
>>> type(price)
<type 'int'>
>>>

6
投票

我认为bdev TJ的答案

price = int(filter(str.isdigit, just))

仅适用于Python2,对于Python3(我检查的是3.7)使用:

price = int ( ''.join(filter(str.isdigit, just) ) )

显然,如前所述,这种方法只会产生一个包含输入字符串中按顺序包含所有数字 0-9 的整数,仅此而已。


4
投票

您可以使用

string.split
功能。

>>> just='Standard Price:20000'
>>> int(just.split(':')[1])
20000

4
投票

我认为最清晰的方法是使用

re.sub()
函数:

import re

just = 'Standard Price:20000'
only_number = re.sub('[^0-9]', '', just)
print(only_number)
# Result: '20000'

2
投票

你可以使用正则表达式

>>> import re
>>> just='Standard Price:20000'
>>> re.search(r'\d+',just).group()
'20000'

参考:

\d
匹配从
0
9

的数字

注意:您的错误

just[0]
计算结果为
S
,因为它是第
0
个字符。因此
S[1:]
返回一个空字符串
''
,因为该字符串的长度为
1
并且长度
1

之后没有其他字符

1
投票

如果您不想使用正则表达式,更粗暴的方法是使用切片。请记住,如果文本结构保持不变,这将适用于提取任何数字。

just = 'Standard Price:20000'
reqChar = len(just) - len('Standard Price:')
print(int(just[-reqChar:]))
>> 20000

0
投票

您使用的内容没有太大区别,但避免正则表达式可以节省额外的导入(i5-8250U)。

import re

def regex():
    dirty = 'Standard Price:20000'
    return re.findall("\\d+", dirty)[0]

def regex_grp():
    dirty = 'Standard Price:20000'
    return re.search(r'\d+', dirty).group()

def isdigit():
    dirty = 'Standard Price:20000'
    return int(''.join(i for i in dirty if i.isdigit()))

def filter_():
    dirty = 'Standard Price:20000'
    return int(''.join(filter(str.isdigit, dirty)))

regex() 1.33 μs ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
regex_grp() 1.4 μs ± 17.9 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
isdigit() 1.73 μs ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
filter_() 1.33 μs ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
© www.soinside.com 2019 - 2024. All rights reserved.