I have a string and I want to extract the numbers from it. 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.
You can filter the string by digits using str.isdigit method,
>>> int(filter(str.isdigit, str1))
3158
For Python3:
int(list(filter(str.isdigit, my_str))[0])
filter is a class and calling it like you did returns a filter object which is an iterable, and int() can't cast a filter object into an int. It seems to me that there is no elegant way (such as in your answer, without using regex) to do this is Python 3. Is there?int(list(filter(str.isdigit, my_str))[0]) for example. If filter returns an iterable, you just have to work with it :)int(''.join(list(filter(str.isdigit, my_str)))) if you want ALL the numbers in the string instead of just the first.listis not needed: int(''.join(filter(str.isdigit, 'test3246')))"3158 reviews 3158asdf 4".This code works fine. There is definitely some other problem:
>>> import re
>>> str1 = "3158 reviews"
>>> print (re.findall('\d+', str1 ))
['3158']
IntVar = int("".join(filter(str.isdigit, StringVar)))
You were quite close to the final answer. Your re.finadall expression was only missing the enclosing parenthesis to catch all detected numbers:
re.findall( '(\d+)', str1 )
For a more general string like str1 = "3158 reviews, 432 users", this code would yield:
Output: ['3158', '432']
Now to obtain integers, you can map the int function to convert strings into integers:
A = list(map(int,re.findall('(\d+)',str1)))
Alternatively, you can use this one-liner loop:
A = [ int(x) for x in re.findall('(\d+)',str1) ]
Both methods are equally correct. They yield A = [3158, 432].
Your final result for the original question would be first entry in the array A, so we arrive at any of these expressions:
result = list(map(int,re.findall( '(\d+)' , str1 )))[0]
result = int(re.findall( '(\d+)' , str1 )[0])
Even if there is only one number present in str1, re.findall will still return a list, so you need to retrieve the first element A[0] manually.
To extract a single number from a string you can use re.search(), which returns the first match (or None):
>>> import re
>>> string = '3158 reviews'
>>> int(re.search(r'\d+', string).group(0))
3158
In Python 3.6+ you can also index into a match object instead of using group():
>>> int(re.search(r'\d+', string)[0])
3158
re module is available in 1.5 and later :).findall method instead of .search. This .findall method always returns a list with string items. The list will contain all the values found and therefore an index is required. It can be treated e.g. always retrieve the last item as the last index from behind: int(re.findall(r'\d+', string)[-1])If the format is that simple (a space separates the number from the rest) then
int(str1.split()[0])
would do it
If the format is that simple YESSS ... I was passing a wrong variable... BTW ... you told me a shortest solution .. thanksAbove solutions seem to assume integers. Here's a minor modification to allow decimals:
num = float("".join(filter(lambda d: str.isdigit(d) or d == '.', inputString)
(Doesn't account for - sign, and assumes any period is properly placed in digit string, not just some english-language period lying around. It's not built to be indestructible, but worked for my data case.)
I am a beginner in coding. This is my attempt to answer the questions. Used Python3.7 version without importing any libraries.
This code extracts and returns a decimal number from a string made of sets of characters separated by blanks (words).
Attention: In case there are more than one number, it returns the last value.
line = input ('Please enter your string ')
for word in line.split():
try:
a=float(word)
print (a)
except ValueError:
pass
My answer does not require any additional libraries, and it's easy to understand. But you have to notice that if there's more than one number inside a string, my code will concatenate them together.
def search_number_string(string):
index_list = []
del index_list[:]
for i, x in enumerate(string):
if x.isdigit() == True:
index_list.append(i)
start = index_list[0]
end = index_list[-1] + 1
number = string[start:end]
return number
del index_list[:]?you can use the below method to extract all numbers from a string.
def extract_numbers_from_string(string):
number = ''
for i in string:
try:
number += str(int(i))
except:
pass
return number
(OR) you could use i.isdigit() or i.isnumeric(in Python 3.6.5 or above)
def extract_numbers_from_string(string):
number = ''
for i in string:
if i.isnumeric():
number += str(int(i))
return number
a = '343fdfd3'
print (extract_numbers_from_string(a))
# 3433
Using a list comprehension and Python 3:
>>> int("".join([c for c in str1 if str.isdigit(c)]))
3158
Use this, THIS IS FOR EXTRACTING NUMBER FROM STRING IN GENERAL.
To get all the numeric occurences.
getting number from string, use list comprehension+isdigit()
test_string = "i have four ballons for 2 kids"
# list comprehension + isdigit() +split()
res = [int(i) for i in test_string.split() if i.isdigit()]
print("The numbers list is : "+ str(res))
To extract numeric values from a string in python
Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string) method.
Convert each number in form of string into decimal number and then find max of it.
import re
def extractMax(input):
# get a list of all numbers separated by lower case characters
# \d+ is a regular expression which means one or more digit
numbers = re.findall('\d+',input)
number = map(int,numbers)
return max(numbers)
if __name__=="__main__":
input = 'sting'
print extractMax(input)
__name__=="__main__" is just a distraction.)
['3158'].