[Tutor] escape codes and filenames (FALSE ALARM
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 25 Nov 2000 17:03:56 -0800 (PST)
On Sat, 25 Nov 2000, Mallett, Roger wrote:
> Thank you very much for the help you did provide, for it was applied to
> solve my original problem.
If you have time, try to switch the slashes in your filelist back to
backslashes and see if your program still works --- I think it was just
those terminating newlines that were causing problems.
Also, the way that Python prints out strings depends if you ask it for a
its string or representation conversion. For example:
###
>>> name = "Roger\\Mallet"
>>> print name
Roger\Mallet
>>> print str(name)
Roger\Mallet
>>> name
'Roger\\Mallet'
>>> print repr(name)
'Roger\\Mallet'
###
Here's something strange --- one way prints with '\\', while the other way
with '\'. The reason for this is because repr() (ideally) returns the
representation of the string: it's what you'd literally type into the
interpreter to get that same value.
repr() doesn't always give different results. For example:
###
>>> f = open('foobar.txt')
>>> print f
<open file 'foobar.txt', mode 'r' at 0x81c76e8>
>>> print repr(f)
<open file 'foobar.txt', mode 'r' at 0x81c76e8>
##
What's important to see is that repr() does give different results for
strings, which can be confusing at first, but useful:
###
>>> print repr("\ttest\tagain")
'\011test\011again'
>>> print str("\ttest\tagain")
test again
###
The reason you were getting different results when you were printing out
those strings is because when you ask Python for a variable, it'll return
its representation: escaped backslashes, quotes and all. So getting a
variable's value is not the same thing as getting its string form. In
most cases, it looks very similar, so be careful.
I hope this helps!