Find all numbers in a string in Python 3 [duplicate]

人走茶凉 提交于 2019-12-13 09:29:08

问题


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]

回答1:


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)

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)



回答2:


Here you have your made up function, explained and detailed.
Since you're a newbie, this is a very simple approach so it can be easily understood.

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


来源:https://stackoverflow.com/questions/33225900/find-all-numbers-in-a-string-in-python-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!