Testing if a variable is an integer or a string; exceptions in __del__
Jeremy Hylton
jeremy at cnri.reston.va.us
Sun May 2 22:17:30 EDT 1999
To answer your specific question specifically, re.match isn't a great
way to test if the input is an integer. In Perl, regular expressions
are a Swiss army knife of sorts -- handy in all sorts of situations.
In Python, you'll find them most handy from string processing (and
even then you'll find that sometimes plain old string.split will do).
A more Pythonic way to check if a string is an integer is to try to
convert it to an integer using string.atoi and then catching the
exception.
try:
self.year = string.atoi(buf[90:94])
except ValueError:
self.year = 0
string.atoi raises a ValueError when passed something like 'Funk', but
watch out for negative numbers.
Another option, since you'll have to convert the genre names to
integers in order to encode them in the mp3 tag anway, is to use the
dictionary that maps genre names to integers. Let's assume genre_dict
is the dictionary and genre_inp is what the user typed.
if genre_dict.has_key(genre_inp):
genre = genre_dict[genre_inp]
else:
try:
genre = string.atoi(genre_inp)
except ValueError:
raise ValueError, "Invalid genre: %s" % genre_inp
Now genre will be the numeric genre value.
Jeremy
More information about the Python-list
mailing list