Most of the questions I\'ve found are biased on the fact they\'re looking for letters in their numbers, whereas I\'m looking for numbers in what I\'d like to be a numberless
You can use range with count to check how many times a number appears in the string by checking it against the 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
You can use any function, with the str.isdigit function, 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 a Regular Expression, like this
>>> import re
>>> def hasNumbers(inputString):
... return bool(re.search(r'\d', inputString))
...
>>> hasNumbers("I own 1 dog")
True
>>> hasNumbers("I own no dog")
False
https://docs.python.org/2/library/re.html
You should better use regular expression. It's 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's 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
alp_num = [x for x in string.split() if x.isalnum() and re.search(r'\d',x) and
re.search(r'[a-z]',x)]
print(alp_num)
This returns all the string that has both alphabets and numbers in it. isalpha() returns the string with all digits or all characters.