-2

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]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Blab
  • 235
  • 2
  • 9
  • Take a look at the `re` module and `split`, where you could split on the operators. – AChampion Oct 20 '15 at 00:04
  • 4
    I *really* don't believe that you've been searching the net for hours. Typing your *exact* question title into Google yields me the answer. – Lynn Oct 20 '15 at 00:07
  • I promise you. Been using at least 2 hours on searching for this. Thanks for fast repons! – Blab Oct 20 '15 at 00:08

2 Answers2

2

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)
user3148185
  • 512
  • 3
  • 8
  • The only thing to add would be if the OP needs a list of ints `result = [int(i) for i in re.findall(r'\d+',string)]` or `result = [int(i) for i in re.split('[+-*/]', string)]` – AChampion Oct 20 '15 at 00:36
0

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
Luis Ávila
  • 689
  • 4
  • 14