I’m working with strings that contain both digits and alphanumerics, or just digits, but not just alphas. In order to test for false matches, I need to check if the strings contain at least one digit, printing an error message if it doesn’t. I have been using the following code:
s = '0798237 sh 523-123-asdjlh'
def contains_digits(s):
for char in list(s):
if char.isdigit():
return True
break
return False
if contains_digits(s) == True:
print s
else:
print 'Error'
Is there a more pythonic or simpler way to do so, or does this suffice? Also, I can’t just check to see if the string is alphanumeric, because the string may contain various symbols (‘-‘, spaces, etc.)
This is one of those places where a regular expression is just the thing:
Little demo:
You could use the
anymethod with.isdigit()as described in @Wallacolloo’s answer, but that’s slower than the simple regular expression:The
ifmethod is on par with the regular expression:But things get worse if the digits appear late in the text:
Timings tested on python 2.6 on Mac OS X 10.7.