determining type

David Fisher python at rose164.wuh.wustl.edu
Wed Mar 22 20:19:48 EST 2000


----- Original Message ----- 
From: "sp00fD" <sp00fD at yahoo.com>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, March 22, 2000 10:53 AM
Subject: determining type


> I'm writing a program in which I've got a couple of dictionaries that
> I'd like to output to a file, but I'd like it to be "pretty". I'm
> trying to write a function to format the dictionary so that when I
> print it, rather than looking like {'foo' : 'bar', 'who' : 'what'}, it
> looks like
> {
> 'foo' : 'bar',
> 'who' : 'what',
> }
> The way that I'm trying to do this is to create a string and loop
> through the dict.keys(), appending to the string. The problem is that
> if it's not a string, but an integer (the key or value) I don't want it
> quoted obviously (I'm adding the quotes manually \"%s\").
> How do I determine if it's a string or int. I've tried:
> if type(key) == "<type \'string\'>":
> but that doesn't seem to work. How do I do this?

This'll do it:

import types

a = 1

if isinstance(a,types.IntType):
    print "it's an int!"
elif isinstance(a,types.StringType):
    print "it's a string!"

Good luck,
David





More information about the Python-list mailing list