Raw Strings with Variables

Chris Rebert clp2 at rebertia.com
Tue Aug 18 20:18:13 EDT 2009


On Tue, Aug 18, 2009 at 5:09 PM, WilsonOfCanada<wwn1 at sfu.ca> wrote:
> You're right, but the moment I append it onto a list, it would become
> C:\\moo.
>
> arrPlaces = []
> intPoint =0
>
> while (len(testline)):
>        testline = fileName.readline()
>        print testline
>        arrPlaces[intPoint].append(testline)
>        intPoint += 1
>
> print arrPlaces
>
>> C:\moo
>> C:\supermoo
>> ['C:\\moo', 'C:\\supermoo']

That's because the list uses repr() rather than str() to stringify its
items when it is output. repr() shows escape sequences rather than the
literal characters and adds the surrounding quote marks, but the
string is not modified upon placement in the container.

Study this interpreter session:
>>> a = r"C:\supermoo"
>>> b = "\t" #a tab character
>>> c = [a, b]
>>> print a #note the lack of quotes in the output
C:\supermoo
>>> print repr(a) #note the quotes and \\
'C:\\supermoo'
>>> print b #we see the literal tab
	
>>> print repr(b) #we see the escape sequence
'\t'
>>> print c #note how this matches the repr() output from earlier
['C:\\supermoo', '\t']
>>> print c[0], c[1], "end" #but the actual strings are the same as before
C:\supermoo 	end

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list