[Tutor] Help with checking for a data type

Kent Johnson kent37 at tds.net
Thu Sep 4 23:26:07 CEST 2008


On Thu, Sep 4, 2008 at 4:56 PM, Spencer Parker <inthefridge at gmail.com> wrote:
> I have a script that is taking a directory list, the script then splits the
> name up by the hyphens in the name.  The first part of the name should be a
> number, but it isn't always a number.  Is there a way to say: if its a
> number then post this data....if not discard?

Tthe isdigit() method of a string provides a simple test. It will
return true if each character is a digit.
if first_part.isdigit():
  # post data

If you want to allow things like '-300' or '1.234' then you can try to
convert to an int or float. Failure will raise a ValueError.
try:
  float(first_part)
  # post data
except ValueError:
  pass

Kent


More information about the Tutor mailing list