在python中只从字符串中获取数字

2024-04-19 12:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我只想从字符串中得到数字。比如我有这样的东西

just='Standard Price:20000'

我只想把它打印出来

20000

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

我试过了

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

我得到了

 ''

最好的办法是什么?我是个笨蛋。


Tags: 字符串数字pricestandard笨蛋just办法
3条回答

您可以使用string.split函数。

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

你可以用RegEx

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

Ref:\d匹配从09的数字

注意:您的错误

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

您可以使用regex:

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

或者

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

相关问题 更多 >