[Tutor] Python file escaping issue?
Sithembewena Lloyd Dube
zebra05 at gmail.com
Mon Feb 22 20:35:00 CET 2010
@spr, thanks for the explanation, especially on representations of strings.
To think that i freely used repr(variable_x) without fully understanding the
meaning and the power of that function..
On Mon, Feb 22, 2010 at 9:37 AM, spir <denis.spir at free.fr> wrote:
> Just a little complement to Steven's excellent explanation:
> On Mon, 22 Feb 2010 10:01:06 +1100
> Steven D'Aprano <steve at pearwood.info> wrote:
> > So if you write a pathname like this:
> > >>> path = 'C:\datafile.txt'
> > >>> print path
> > C:\datafile.txt
> > >>> len(path)
> > 15
> > It *seems* to work, because \d is left as backlash-d. But then you do
> > this, and wonder why you can't open the file:
> I consider this misleading, since it can only confuse newcomers. Maybe
> "lonely" single backslashes (not forming a "code" with following
> character(s)) should be invalid. Meaning literal backslashes would always be
> doubled (in plain, non-raw, strings). What do you think?
> > But if the escape is not a special character:
> > >>> s = 'abc\dz' # nothing special
> > >>> print s
> > abc\dz
> > >>> print repr(s)
> > 'abc\\dz'
> > >>> len(s)
> > 6
> > The double backslash is part of the *display* of the string, like the
> > quotation marks, and not part of the string itself. The string itself
> > only has a single backslash and no quote marks.
> This "display" is commonly called "representation", thus the name of the
> function repr(). It is a string representation *for the programmer* only,
> both on input and output:
> * to allow one writing, in code itself, string literal constants containing
> special characters, in a practical manner (eg file pathes/names)
> * to allow one checking the actual content of string values, at testing
> The so-called interactive interpreter outputs representations by default.
> An extreme case:
> >>> s = "\\"
> >>> s
> >>> print s, len(s)
> \ 1
> >>> print repr(s), len(repr(s))
> '\\' 4
> The string holds 1 char; its representation (also a string, indeed) holds
> > The best advice is to remember that Windows allows both forward and
> > backwards slashes as the path separator, and just write all your paths
> > using the forward slash:
> > 'C:/directory/'
> > 'C:textfile.txt'
> Another solution is to take the habit to always escape '\' by doubling it.
> la vita e estrany
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Sithembewena Lloyd Dube
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor