Q:

python get numbers from string

>>> str = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in str.split() if s.isdigit()]
[23, 11, 2]
1
# initializing string  
test_string = "There are 2 apples for 4 persons"
  
# printing original string  
print("The original string : " + test_string) 
  
# using List comprehension + isdigit() +split() 
# getting numbers from string  
res = [int(i) for i in test_string.split() if i.isdigit()] 
  
# print result 
print("The numbers list is : " + str(res)) 
1
string = "abc123"
# Method 1
''.join(char for char in string if char.isdigit())

#Method 2
import re
re.sub("[^0-9]", "", string)
1

New to Communities?

Join the community