Reputation: 157
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?
Upvotes: 0
Views: 713
Reputation: 1644
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()
Upvotes: 1
Reputation: 33661
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
Upvotes: 1
Reputation: 1998
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
Upvotes: 1