-3

I'm trying to extract numbers from a string like "12+13".

When I extract only the numbers from it into a list it becomes [1,2,1,3]

actually I want the list to take the numbers as [12,13] and 12,13 should be integers also.

I have tried my level best to solve this,the following is the code

but it still has a disadvantage .

I am forced to put a space at the end of the string...for it's correct functioning.


My Code

def extract(string1):
    l=len(string1)
    pos=0
    num=[]
    continuity=0
    for i in range(l):
        
        if string[i].isdigit()==True:
            continuity+=1

        else:
        
            num=num+ [int(string[pos:continuity])]
            continuity+=1
            pos=continuity
    return num

string="1+134-15 "#added a spaces at the end of the string

num1=[]

num1=extract(string)

print num1
Community
  • 1
  • 1
Star Rider
  • 107
  • 1
  • 6

5 Answers5

1

This will work perfectly with your situation (and with all operators, not just +):

>>> import re
>>> equation = "12+13"
>>> tmp = re.findall('\\b\\d+\\b', equation)
>>> [int(i) for i in tmp]
[12, 13]

But if you format your string to be with spaces between operators (which I think is the correct way to go, and still supports all operators, with a space) then you can do this without even using regex like this:

>>> equation = "12 + 13"
>>> [int(s) for s in equation.split() if s.isdigit()]
[12, 13]

Side note: If your only operator is the + one, you can avoid regex by doing:

>>> equation = "12+13"
>>> [int(s) for s in equation.split("+") if s.isdigit()]
[12, 13]
Idos
  • 15,053
  • 14
  • 60
  • 75
  • @IronFist I offered two solutions... I should probably add a third which is using what intboolstring did, though it works just for "+" which isn't generic at all. – Idos Jan 07 '16 at 15:40
0

The other answer is great (as of now), but I want to provide you with a detailed explanation. What you are trying to do is split the string on the "+" symbol. In python, this can be done with str.split("+").

When that translates into your code, it turns out like this.

ourStr = "12+13"
ourStr = ourStr.split("+")

But, don't you want to convert those to integers? In python, we can use list comprehension with int() to achieve this result.

To convert the entire array to ints, we can use. This pretty much loops over each index, and converts the string to an integer.

str = [int(s) for s in ourStr]

Combining this together, we get

ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr]

But lets say their might be other unknown symbols in the array. Like @Idos used, it is probably a good idea to check to make sure it is a number before putting it in the array.

We can further refine the code to:

ourStr = "12+13"
ourStr = ourStr.split("+")
ourStr = [int(s) for s in ourStr if s.isdigit()]
intboolstring
  • 6,891
  • 5
  • 30
  • 44
0

You can just use Regular Expressions, and this becomes very easy:

>>> s = "12+13"
>>> import re
>>> re.findall(r'\d+',s)
['12', '13']

basically, \d matches any digit and + means 1 or more. So re.findall(r'\d+',s) is looking for any part of the string that is 1 or more digits in a row and returns each instance it finds!

in order to turn them to integers, as many people have said, you can just use a list comprehension after you get the result:

result = ['12', '13']
int_list = [int(x) for x in result]

python regex documentation

Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128
  • 1
    I readlly don't see any necessity to use `regex` in this case, plus OP wants list of integers – Iron Fist Jan 07 '16 at 15:36
  • You're right, you don't need to as you can just use split as long as it is only one delimiter. But if there is any oddity to the pattern, regex is probably going to be the best solution. Plus this is quick and easy, and I don't see a reason not to use it. I was just adding additional options as there were already two answers that were more narrow – Ryan Saxe Jan 07 '16 at 16:10
  • I really prefer to keep `regex` for use of complex pattern extraction...as they have powerful algorithms to do so and using them in this case just to extract numbers where you can split over `+` is a waste of use of such core library, in my opinion...but remember to update your answer so it reflects OP requirements, which is a list of integers and not strings – Iron Fist Jan 07 '16 at 16:14
  • @IronFist, that makes sense. I chose to use regex as he really didn't specify if it was a constant delimiter and so this was the only solution I could come up with that guarenteed to work that was not already posted. My answer has been updated accordingly – Ryan Saxe Jan 07 '16 at 16:18
0

This can be solved with just list comprehension or built-in methods, no need for regex:

s = '12+13+14+15+16'
l = [int(x) for x in s.split('+')]
l = map(int, s.split('+'))
l = list(map(int, s.split('+'))) #If Python3
[12, 13, 14, 15, 16]

If you are not sure whether there are any non-digit strings, then just add condition to the list comprehension:

l = [int(x) for x in s.split('+') if x.isdigit()]
l = map(lambda s:int(s) if s.isdigit() else None, s.split('+')) 
l = list(map(lambda s:int(s) if s.isdigit() else None, s.split('+'))) #If python3

Now consider a case where you could have something like:

s = '12 + 13 + 14+15+16'
l = [int(x.strip()) for x in s.split('+') if x.strip().isdigit()]#had to strip x for any whitespace
l = (map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))
l = list(map(lambda s:int(s.strip()) if s.strip().isdigit() else None, s.split('+'))) #Python3
[12, 13, 14, 15, 16]

Or:

l = [int(x) for x in map(str.strip,s.split('+')) if x.isdigit()]
l = map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))
l = list(map(lambda y:int(y) if y.isdigit() else None, map(str.strip,s.split('+')))) #Python3
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
0

I have made a function which extracts number from a string.

def extract(string1):
    string1=string1+" "
    #added a spaces at the end of the string so that last number is also    extracted
    l=len(string1)
    pos=0
    num=[]
    continuity=0
    for i in range(l):

        if string1[i].isdigit()==True:
            continuity+=1

        else:

            if pos!=continuity:
                ''' This condition prevents consecutive execution
                of else part'''

                num=num+ [int(string1[pos:continuity])]

            continuity+=1
            pos=continuity
    return num

string="ab73t9+-*/182"

num1=[]

num1=extract(string)

print num1
Star Rider
  • 107
  • 1
  • 6