2

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.

mpx
  • 3,081
  • 2
  • 26
  • 56
  • 4
    use regex `\d+` – Countour-Integral Feb 16 '21 at 10:26
  • 4
    Does this answer your question? [How to extract numbers from a string in Python?](https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python) – costaparas Feb 16 '21 at 10:31
  • The optimal solution depends on the structure of the string. For example, if there are always 4 letters before the integer, int(s[4:]) is better than a regex :) – kol Feb 16 '21 at 10:32
  • @costaparas Nope, the problem is based on word and number separated by space – mpx Feb 16 '21 at 10:33
  • @balandongiv Please give us a couple of example strings. – kol Feb 16 '21 at 10:34
  • 1
    Hi @kol, the problem consist of more than single digit (e.g., S1 S11 S111 etc). But based on your suggestion, I think I can omit the first letter and convert the rest of the str as int. Thanks for the idea btw – mpx Feb 16 '21 at 10:35

2 Answers2

1

Use Regex:

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


## output
['1']

Hossein Heydari
  • 1,439
  • 9
  • 28
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:])

kol
  • 27,881
  • 12
  • 83
  • 120