repr on a string

Terry Reedy tjreedy at udel.edu
Mon Jun 2 12:15:11 EDT 2003


"Alexander Schmolck" <a.schmolck at gmx.net> wrote in message
news:yfswug4yeka.fsf at black132.ex.ac.uk...
> David Shochat <shochatd at yahoo.com> writes:
> > for dir in sys.path:
> >     if string.find(os.path.abspath(dir), 'PyTools') != -1:
> >         print 'removing', repr(dir)
> >         sys.path.remove(dir)
> >
> > In the 3d line, why does he not just say:
> >   print 'removing', dir

> My guess would be: mainly to put the name into (the right; ' or ")
quotation
> marks and make sure that funny characters are escaped. I think using
`str`
> here would be equally OK, although then the user wouldn't be able to
tell
> apart e.g. "that filename " from "that filename".

Instead of asking or guessing, one can try things out in the
interactive interpreter:

>>> d = os.getcwd()
>>> print 'str:', d, '  repr:', repr(d)
str: C:\Python22   repr: 'C:\\Python22'

The difference is having the filename quoted or not in the output.  If
one wants the former, repr(dir) is easier than "'"+dir+"'" (thats
double quote, single quote, double quote, all twice), although the
latter avoids the \ doubling and gives the option of '"' instead.

>>> print "'"+d+"'", '"'+d+'"'
'C:\Python22' "C:\Python22"

so I would prefer this for production code.


Terry J. Reedy






More information about the Python-list mailing list