Breaking

Code Gripper
Responsive Advertisement
  • Home
Homenumber

How to get only number from string in Python?

byMahabubur Rahman -September 10, 2021
0

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
Tags number Python string
  • Facebook
  • Twitter

You may like these posts

Post a Comment

Previous Post Next Post

Follow Us

Popular Posts

aggregate

How to efficiently count filtered documents in MongoDB $group operator

byDev3-January 13, 2023

How to get current day date in JavaScript

August 19, 2021

How to fix Error: laravel.log could not be opened?

January 11, 2022

Django - cannot import name 'config' from 'decouple'

January 10, 2023

Subscribe Us

Facebook

Categories

Main Tags

Code Gripper

September 30, 2023

Total Pageviews

Search This Blog

CODE GRIPPER

Code Gripper
CODE GRIPPER

  • Home
  • Python
  • PHP

Menu Footer Widget

  • Home
  • About
  • Contact Us
Code Gripper

About Us

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's.

Categories

Main Tags

Latest Posts

Most Popular

How to efficiently count filtered documents in MongoDB $group operator

January 13, 2023

How to get current day date in JavaScript

August 19, 2021

How to fix Error: laravel.log could not be opened?

January 11, 2022
Design by Blogger | Distributed by Gooyaabi
  • Home
  • About Us
  • Contact Us
  • RTL Version

Contact Form