How to get only number from string in Python?

engrmahabub
Mahabubur Rahman
Published on Oct, 19 2023 1 min read 0 comments
image

We can use some methods to get the only number from a string.

  • int
  • join
  • filter
  • str.isdigit

Use the following code and get integer value from string

views = '100 views'
views = int(''.join(filter(str.isdigit, views)))
print(views)
Output: 100

 

views = ''
views = int(''.join(filter(str.isdigit, views)))
print(views)

Throw an exception as below.

 

Traceback (most recent call last):
  File "<input>", line 2, in <module>
ValueError: invalid literal for int() with base 10: ''

 

But is string have no number above code will throw an exception, so in this case we can use try-except to handle exception as bellow -

 

views = '100 views'

try:                
    views = int(''.join(filter(str.isdigit, views)))
except:
    views = 0

print(views)
Output : 100
views = ''

try:                
    views = int(''.join(filter(str.isdigit, views)))
except:
    views = 0

print(views)

 

Output : 0
0 Comments