repr on a string

Gerrit Holl gerrit at nl.linux.org
Sun Jun 1 17:27:32 EDT 2003


David Shochat schreef op zondag  1 juni om 22:21:17 +0000:
> The Library Reference says this about built-in repr():
>  Return a string containing a printable representation of an object.
> 
> While studying Programming Python, 2nd Ed. Example 2-18, p. 84, I was
> wondering what the point was of applying repr to a component (dir) of 
> sys.path. Isn't it after all, already a printable string? Ok, so 
> what does it mean to take repr of a printable string, and why does 
> the author want to here? Are we worried that the path contains an 
> unprintable directory name or something?
> 
> I tried this:
> >>> str = 'dog'
> >>> str
> 'dog'
> >>> repr(str)
> "'dog'"
> 
> We now seem to have a string with quote characters as its first 
> and last components. I would have thought that the operation of 
> making a printable representation of something that is already 
> printable would be the identify function. Could someone
> explain precisely what is going on here?

'repr' creates a reprentation that can be eval()ed, if possible. That's
why the quotes are necessary. When you type the name of an object in
the active interpreter, it also does a repr. When you type "print object"
it doesn't:

  8 >>> s = 'dog'
  9 >>> s
'dog'
 10 >>> print s
dog
 11 >>> repr(s)
"'dog'"
 12 >>> print repr(s)
'dog'
 13 >>> print repr(repr(repr(repr(s))))
'\'"\\\'dog\\\'"\''
 14 >>> eval(repr(s))
'dog'
 15 >>> print eval(repr(s))
dog
 18 >>> print repr(s)[0]
'
 20 >>> repr({})
'{}'
 21 >>> repr(0)
'0'
 22 >>> repr(repr)
'<built-in function repr>'

Hope this helps!

yours,
Gerrit.

--
 If a father give a present to his daughter -- either marriageable
or a prostitute (unmarriageable) -- and then die, then she is to receive a
portion as a child from the paternal estate, and enjoy its usufruct so
long as she lives. Her estate belongs to her brothers. 
        -- Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list