determining type

Clarence Gardner clarence at netlojix.com
Fri Mar 24 10:19:05 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?

Your example is almost correct, but you were no doubt misled by
what you saw in the interactive mode.  You want
  if type(key) == type(""):

The "<type 'string'>" is what the return value of type("") looks like
when *it* is converted to a string (e.g., for printing), but is not the
actual value that the type function returned.




More information about the Python-list mailing list