Check if string contains a number

Most of the questions I have found are biased towards the fact that they are looking for letters in their numbers, while I am looking for numbers in what I would like to be a countless string. I need to enter a string and check if it contains any numbers and whether it rejects.

The isdigit() function returns True only if ALL characters are numbers. I just want to see if the user entered a number, for example the sentence "I have 1 dog" or something like that.

Any ideas?

+148
python string
Nov 08 '13 at
source share
14 answers

You can use any , with str.isdigit , like this

 >>> def hasNumbers(inputString): ... return any(char.isdigit() for char in inputString) ... >>> hasNumbers("I own 1 dog") True >>> hasNumbers("I own no dog") False 

Alternatively you can use regex like

 >>> import re >>> def hasNumbers(inputString): ... return bool(re.search(r'\d', inputString)) ... >>> hasNumbers("I own 1 dog") True >>> hasNumbers("I own no dog") False 
+221
Nov 08 '13 at
source share

You can use a combination of any and str.isdigit :

 def num_there(s): return any(i.isdigit() for i in s) 

The function will return True if there is a digit in the string, otherwise False .

Demo:

 >>> king = 'I shall have 3 cakes' >>> num_there(king) True >>> servant = 'I do not have any cakes' >>> num_there(servant) False 
+36
Nov 08 '13 at
source share

https://docs.python.org/2/library/re.html

Better use regex. It is much faster.

 import re def f1(string): return any(i.isdigit() for i in string) def f2(string): return re.search('\d', string) # if you compile the regex string first, it even faster RE_D = re.compile('\d') def f3(string): return RE_D.search(string) # Output from iPython # In [18]: %timeit f1('assdfgag123') # 1000000 loops, best of 3: 1.18 µs per loop # In [19]: %timeit f2('assdfgag123') # 1000000 loops, best of 3: 923 ns per loop # In [20]: %timeit f3('assdfgag123') # 1000000 loops, best of 3: 384 ns per loop 
+23
Aug 6 '15 at 16:40
source share

use

  str.isalpha () 

Link: https://docs.python.org/2/library/stdtypes.html#str.isalpha

Returns true if all the characters in the string are alphabetic and there is at least one character, otherwise false.

+19
Jun 28 '15 at 2:20
source share

You can apply the isdigit () function to each character in a string. Or you can use regular expressions.

Also I found How to find a single number in a string in Python? with very suitable ways to return numbers. The solution below is from the answer to this question.

 number = re.search(r'\d+', yourString).group() 

As an alternative:

 number = filter(str.isdigit, yourString) 

For more information, check out the regex document: http://docs.python.org/2/library/re.html.

Change: Returns real numbers, not a boolean, so the answers above are more true for your case.

The first method returns the first digit and subsequent consecutive digits. Thus, 1.56 will be returned as 1. 10000 will be returned as 10. 0207-100-1000 will be returned as 0207.

The second method does not work.

To extract all numbers, periods, and commas and not lose inconsistent numbers, use:

 re.sub('[^\d.,]' , '', yourString) 
+6
Nov 08 '13 at 12:44
source share

How about this?

 import string def containsNumber(line): res = False try: for val in line.split(): if (float(val.strip(string.punctuation))): res = True break except ValueError, e: pass return res print containsNumber('234.12 a22') # returns True print containsNumber('234.12L a22') # returns False print containsNumber('234.12, a22') # returns True 
+1
Nov 08 '13 at 12:52
source share

You can use a range with a quantity to check how many times a number appears in a string by comparing it to a range:

 def count_digit(a): sum = 0 for i in range(10): sum += a.count(str(i)) return sum ans = count_digit("apple3rh5") print(ans) #This print 2 
+1
Sep 29 '17 at 19:20
source share

You can use the NLTK method for this.

This will find "1" and "one" in the text:

 import nltk def existence_of_numeric_data(text): text=nltk.word_tokenize(text) pos = nltk.pos_tag(text) count = 0 for i in range(len(pos)): word , pos_tag = pos[i] if pos_tag == 'CD': return True return False existence_of_numeric_data('We are going out. Just five you and me.') 
+1
06 Oct. '17 at 11:29 on
source share

You can do it as follows:

if a_string.isdigit(): do_this() else: do_that()

https://docs.python.org/2/library/stdtypes.html#str.isdigit

Using .isdigit() also means that you do not need to resort to exception handling (try / exclude ) in cases where you need to use list comprehension (try / exclude is not possible in list comprehension).

+1
Mar 15 '18 at 17:00
source share

A simpler way to decide how

 s = '1dfss3sw235fsf7s' count = 0 temp = list(s) for item in temp: if(item.isdigit()): count = count + 1 else: pass print count 
0
Jun 15 '18 at 5:49
source share

I am surprised that no one mentioned this combination of any and map :

 def contains_digit(s): isdigit = str.isdigit return any(map(isdigit,s)) 

in Python 3, it is probably the fastest (with the possible exception of regular expressions), because it does not contain any loop (and function aliases avoid its search in str ).

Do not use this in Python 2, since map returns a list that breaks any short circuit

0
Sep 20 '18 at 21:32
source share
 import string import random n = 10 p = '' while (string.ascii_uppercase not in p) and (string.ascii_lowercase not in p) and (string.digits not in p): for _ in range(n): state = random.randint(0, 2) if state == 0: p = p + chr(random.randint(97, 122)) elif state == 1: p = p + chr(random.randint(65, 90)) else: p = p + str(random.randint(0, 9)) break print(p) 

This code generates a sequence of size n that contains at least uppercase letters, lowercase letters and numbers. Using a while loop, we guaranteed this event.

0
Oct 05 '18 at 12:46
source share

You can use the set intersection property to check if a string contains any digits. set() any string converts each character of the string as separate elements of the set.

 >>> s = 'Abcd123#' >>> s {'#', '1', '2', '3', 'A', 'b', 'c', 'd'} >>> if len(set('0123456789').intersection(set(s))): ... print('string contains number') string contains number 
0
Jul 24. '19 at 18:14
source share

any and ord can be combined to achieve the goal, as shown below.

 >>> def hasDigits(s): ... return any( 48 <= ord(char) <= 57 for char in s) ... >>> hasDigits('as1') True >>> hasDigits('as') False >>> hasDigits('as9') True >>> hasDigits('as_') False >>> hasDigits('1as') True >>> 

A couple of points about this implementation.

  1. any them is better, because it works as an expression of a short circuit in the C language and will return a result as soon as it can be determined, i.e. in the case of the string 'a1bbbbbbc' 'b and' c will not even be compared.

  2. ord better because it provides more flexibility, for example, control numbers only between "0" and "5" or any other range. For example, if you want to write a validator for the hexadecimal representation of numbers, you would like the string to have alphabets only in the range from "A" to "F".

0
Jul 24 '19 at 18:24
source share



All Articles