determining type

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Wed Mar 22 12:50:38 EST 2000


sp00fD wrote in comp.lang.python:
> 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?

if type(key) == type(""):
or 
import types
if type(key) == types.StringType:

Or, better yet, print the repr() of the value.

So the pretty print could look something like:

def pretty_print(dict):
   print '{'
   for item in dict.items():
       print repr(item[0]), ':', repr(item[1])
   print '}'
   
-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
  7:48pm  up 16 days,  8:09,  8 users,  load average: 1.20, 1.10, 1.08



More information about the Python-list mailing list