yet 'nother newbie question
Ivan Van Laningham
ivanlan at callware.com
Sat Nov 27 15:02:20 EST 1999
Hi All--
"William J. King" wrote:
>
> Hi:
>
> When passing an argument to a function etc. -- how does one determine
> that it is
> an integer that is being passed and not a string for example... Is there
> something
> available to determine it's type. The only way I can figure is to use
> 'try' and
> 'except' for a partial solution:
>
> try:
> x = x + "" # suceeds then its a string -- if so
> x = string.atoi(x)
> except:
> x = x + 0 #This sort of partially ensures that int is passed.....
>
> or if you have the reverse situation?...
>
> Hmmm -- It seems python knows the difference internally, how can I
> determine
> types and work with variables without having to resort to exception
> checking...
> Hope this makes sense... Thanks.....
>
type(x)
That is,
if type(x) == type(""):
print "I'm a string"
elif type(x) == type(0):
print "I'm an integer"
else:
print "I'm something else"
type() returns a repr (a printable string) object that might look like
this:
<type 'string'>
There is a module (types) that you can import which has shortcuts in it
so that you can call
if type("")==StringType:
blah blah
but I generally don't bother, since it saves almost nothing on typing.
<and-we-all-know-keystrokes-determine-reality>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan at callware.com
ivanlan at home.com
http://www.pauahtun.org
See also:
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps: Cu Chi, Class of '70
Author: Teach Yourself Python in 24 Hours
----------------------------------------------
More information about the Python-list
mailing list