新手在这里,已经在网上搜索了几个小时以寻求答案。
string = "44-23+44*4522" # string could be longer
我如何使它成为一个列表,所以输出是:
[44, 23, 44, 4522]
使用 AChampion 建议的正则表达式,您可以执行以下操作。
string = "44-23+44*4522"
import re
result = re.findall(r'\d+',string)
r'' 表示原始文本,'\d' 查找十进制字符,+ 表示出现 1 次或多次。如果您希望字符串中的浮点数不希望被分隔,则可以用句点“.”括起来。
re.findall(r'[\d\.]+',string)
在这里你有你的功能,解释和详细。
由于您是新手,因此这是一种非常简单的方法,因此很容易理解。
def find_numbers(string):
list = []
actual = ""
# For each character of the string
for i in range(len(string)):
# If is number
if "0" <= string[i] <= "9":
# Add number to actual list entry
actual += string[i]
# If not number and the list entry wasn't empty
elif actual != "":
list.append(actual);
actual = "";
# Check last entry
if actual != "":
list.append(actual);
return list