Detect numbers in string
value = 'ad.41.bd'
if len(v开发者_StackOverflow社区alue) == len(value.strip({0,1,2,3,4,5,6,7,8,9})):
# no numbers
else:
# numbers present
There a cleaner way of detecting numbers in a string in Python?
What about this?
import re
if not re.search('\d+', value):
# no numbers
else:
# numbers present
>>> value="ab3asdf"
>>> any(c.isdigit() for c in value)
True
>>> value="asf"
>>> any(c.isdigit() for c in value)
False
>>> value = 'ad.41.bd'
>>> any(map(lambda c:c.isdigit(),value))
True
EDIT:
>>> value="1"+"a"*10**6
>>> any(map(lambda c:c.isdigit(),value))
True
>>> from itertools import imap
>>> any(imap(lambda c:c.isdigit(),value))
True
map took 1 second (on old python) imap was instant because imap returns a generator. note often in the real world there is a higher probability of the number being at the end of the file name.
from string import digits
def containsnumbers(value):
return any(char in digits for char in value)
EDIT:
And just for thoroughness:
any(c.isdigit()):
>>> timeit.timeit('any(c.isdigit() for c in value)', setup='value = "abcd1"')
1.4080650806427002
any(c in digits):
>>> timeit.timeit('any(c in digits for c in value)', setup='from string import digits; value = "abcd1"')
1.392179012298584
re.search (1 or more digits):
>>> timeit.timeit("re.search('\d+', value)", setup='import re; value = "abcd1"')
1.8129329681396484
re.search (stop after one digit):
>>> timeit.timeit("re.search('\d', value)", setup='import re; value = "abcd1"')
1.599431037902832
re.match (non-greedy):
>>> timeit.timeit("re.match(r'^.*?\d', value)", setup='import re; value = "abcd1"')
1.6654980182647705
re.match(greedy):
>>> timeit.timeit("re.match(r'^.*\d', value)", setup='import re; value = "abcd1"')
1.5637178421020508
any(map()):
>>> timeit.timeit("any(map(lambda c:c.isdigit(),value))", setup='value = "abcd1"')
1.9165890216827393
any(imap()):
>>> timeit.timeit("any(imap(lambda c:c.isdigit(),value))", setup='from itertools import imap;value = "abcd1"')
1.370448112487793
Generally, the less complex regexps ran more quickly. c.isdigit()
and c in digits
are almost equivalent. re.match
is slightly faster than re.search
. map()
is the slowest solution, but imap()
was the fastest (but within rounding error of any(c.isdigit)
and any(c in digits)
.
You can use a regular expression:
import re
# or if re.search(r'\d', value):
if re.match(r'^.*?\d', value):
# numbers present
else:
# no numbers
if not any(c.isdigit() for c in value)
# no numbers
else:
# numbers present
To detect signs in the numbers, use the ?
operator.
import re
if not re.search('-?\d+', value):
# no numbers
else:
# numbers present
If you want to know how big is the difference, you can use re.sub()
import re digits_num = len(value) - len(re.sub(r'\d','',value)) if not digits_num: #without numbers else: #with numbers - or elif digist_num == 3
精彩评论