在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)