在Python 3中查找字符串中的所有数字 [英] Find all numbers in a string in Python 3

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

问题描述

这里的新手,已经在网上搜索了好几个小时了.

Newbie here, been searching the net for hours for an answer.

string = "44-23+44*4522" # string could be longer

我如何使其成为列表,所以输出为:

How do I make it a list, so the output is:

[44, 23, 44, 4522]

推荐答案

使用AChampion建议的正则表达式,您可以执行以下操作.

Using the regular expressions as suggested by AChampion, you can do the following.

string = "44-23+44*4522"
import re
result = re.findall(r'\d+',string)

r''表示原始文本,'\ d'表示十进制字符,而+表示1次或多次.如果您希望字符串中的浮点数不希望被分开,则可以使用句号."括起来.

The r'' signifies raw text, the '\d' find a decimal character and the + signifies 1 or more occurrences. If you expect floating points in your string that you don't want to be separated, you might what to bracket with a period '.'.

re.findall(r'[\d\.]+',string)

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

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