repr on a string

Alexander Schmolck a.schmolck at
Sun Jun 1 23:58:54 CEST 2003

David Shochat <shochatd at> writes:

> 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

Haven't got the book, so I can't comment on the specific example, but see

> 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?
> Thanks.
> -- David

I think you're maybe confused about the difference between `repr` and `str`:

>>> str("a string")
'a string'
>>> repr("a string")
"'a string'"

`str` is there to create a nice human-readable string representation of an

`repr`, on the other hand gives you the "canonical" string representation of
an object, so that in most cases ``eval(repr(object)) == object``. It is what
an interactive python shell uses to print the results of every command you
enter. This is really rather handy because it means that you can typically
just cut and paste an output into the input prompt and you will get the same

In other words ``str(foo)`` is usually more concise and readable (and hence
useful for end-user output), whereas ``repr(foo)`` typically contains more
information (and is hence useful in interactive sessions or for debugging


More information about the Python-list mailing list