Chris Chris - 1 month ago 7
Python Question

How to cast a int from string that contains not only numbers

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?

Answer

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