repr on a string

Steven Taschuk staschuk at telusplanet.net
Mon Jun 2 05:38:37 CEST 2003


Quoth David Shochat:
  [...]
> Anyway, here is a fragment of the book example I was 
> referring to, with a bit more context:
> 
> 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
> 
> Why the call to repr() here?

I don't have the book either, but at a guess, this is intended to
make sure no weirdness gets printed, such as terminal control
characters.

One (somewhat) common example of the bad things that can occur
when arbitrary strings are printed: if you have a python script
starting with
    #!/usr/bin/env python
(which can be used on Unixy systems to make the script get run by
Python when it is invoked directly), and someone has turned the
line ends in the file into CR LF pairs (say, by editing it with a
Windows text editor), then env tries to run a program called
'python\r'.  That fails, printing the message
    : No such file or directory
which is quite puzzling the first time you see it.  What's
happened is that env printed
    'python\r: No such file or directory'
and the CR moved the print position back to the start of the line,
so the following characters overwrite the preceding ones.

You'd get the same behaviour with
    progname = 'python\r'
    print progname, ': No such file or directory'
Using repr avoids this; the repr of a string contains only ASCII
printable characters.

-- 
Steven Taschuk                                7\ 7'Z {&~         .
staschuk at telusplanet.net                        Y r          --/hG-
                                            (__/ )_             1^1`





More information about the Python-list mailing list