A way of checking if a string contains a number
Larry Bates
larry.bates at websafe.com
Wed Dec 12 17:42:39 EST 2007
Hamish wrote:
> Hey
>
> I'm new to python, but I have used a fair bit of C and Perl
>
> I found Perls regex's to be very easy to use however I don't find
> Pythons regexes as good.
>
> All I am trying to do is detect if there is a number in a string.
>
> I am reading the string from an excel spread sheet using the xlrd
> module
>
> then I would like to test if this string has a number in it
>
> ie.
> import xlrd
> import re
>
> doesHaveNumber = re.compile('[0-9]')
> string1 = ABC 11
>
> regularExpressionCheck = doesHaveNumber.search(string1)
>
> This will get the right result but then I would like to use the result
> in an IF statement and have not had much luck with it.
>
> if regularExpressionCheck != "None"
> print "Something"
>
> the result is that it prints every line from the spreadsheet to output
> but I only want the lines from the spreadsheet to output.
>
> Is there a way I can drop the regular expression module and just use
> built in string processing?
>
> Why si the output from checks in teh re module either "None" or some
> crazy memory address? Couldn't it be just true or false?
>
>
>
>
>
>
>
regularExpressionCheck won't ever contain the characters "None". The result
if doesHaveNumber.search(string1) is a match object not a string. IMHO regular
expressions are overkill for the task you describe. You may be better served to
just try to convert it to whatever number you want.
try:
value=int(string1)
except ValueError:
# do whatever you want for non integers here
else:
# do whatever you want for integers here
Or use string methods:
if string1.isdigit():
print "digits found"
else:
print "alphas found"
-Larry
More information about the Python-list
mailing list