Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Number from String in Python

I am new to Python and I have a String, I want to extract the numbers from the string. For example:

str1 = "3158 reviews" print (re.findall('\d+', str1 )) 

Output is ['4', '3']

I want to get 3158 only, as an Integer preferably, not as List.

like image 290
Umair Ayub Avatar asked Nov 09 '14 06:11

Umair Ayub


People also ask

How do I extract numbers from a string in Python?

To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

How do I print a number in a string in Python?

Use the syntax print(int("STR")) to return the str as an int , or integer. How to Convert Python Int to String: To convert an integer to string in Python, use the str() function.


1 Answers

You can filter the string by digits using str.isdigit method,

>>> int(filter(str.isdigit, str1)) 3158 
like image 118
Vishnu Upadhyay Avatar answered Sep 19 '22 12:09

Vishnu Upadhyay