Extract integer from string with Python

Viewed 245

May I know other approach to extract the int from a string.

str_int='S1'

int ( "".join ( [xx for xx in list ( str_int) if xx.isdigit ()] ) )

I think my current approach is overkill. Should this post is considered duplicate,please link me to the appropriate OP.

2 Answers

Use Regex:

import re
str_int='S1'
my_digits = re.findall(r'\d+', str_int)
print(my_digits)


## output
['1']

"the problem consist of more than single digit (e.g., S1 S11 S111 etc)"

Simply remove the first character and convert the rest to integer: int(s[1:])

Related