0

Casting a string is easy:

string1 = "12"
int1 = int(string1)

But what if I want to extract the int from

string1 = "12 pieces"

The cast should return 12. Is there a pythonic way to do that and ignore any chars that are not numbers?

Chris
  • 157
  • 2
  • 11

3 Answers3

1

How about this?

>>> string1 = "12 pieces"
>>> y = int(''.join([x for x in string1 if x in '1234567890']))
>>> print(y)
12

or better yet:

>>> string1 = "12 pieces"
>>> y = int(''.join([x for x in string1 if x.isdigit() ]))
>>> print(y)
12
Brian
  • 1,988
  • 1
  • 14
  • 29
1

Is there a way to do that and ignore any chars that are not numbers?

Ignoring anything but a digit is, probably, not a good idea. What if a string contains "12 pieces 42", should it return 12, 1242, [12, 42], or raise an exception?

You may, instead, split the string and convert the first element to an int:

In [1]: int('12 pieces'.split()[0])
Out[1]: 12
awesoon
  • 32,469
  • 11
  • 74
  • 99
1

Assuming that the first part of the string is a number, one way to do this is to use a regex match:

import re

def strint(str):
    m=re.match("^[0-9]+", str)
    if m:
        return int(m.group(0))
    else:
        raise Exception("String does not start with a number")

The advantage of this approach is that even strings with just numbers can be cast easily, so you can use this function as a drop in replacement to int()

pragman
  • 1,564
  • 16
  • 19