backslashes in lists
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Mar 12 18:05:18 EDT 2007
En Mon, 12 Mar 2007 12:30:59 -0300, Fabio Gomes <flgoms at hotmail.com>
escribió:
> Nice, Lucas. But help me again, please. What about "echoing" the
> list:>>> str(alist).replace('\\\\','\\')"['a', 'b', 'c:\\some\\path']"
The \ character is used as an escape character, to represent some
non-printable chars and other special purposes.
By example, '\n' consists of ONLY ONE character, a "linefeed" (or "new
line") character.
py> txt = "Hello\nworld!"
py> len(txt)
12
py> print txt
Hello
world!
12 = 5 for "Hello" plus new line (1 char) plus 5 for "world" plus 1 final
"!"
'\t' is a tab character, '\x7E' is a tilde ~, '\'' is a single quote...
(If you want the whole story, see http://docs.python.org/ref/strings.html)
To represent a SINGLE backslash inside a string, you have to use '\\'
py> bs = '\\'
py> print len(bs)
1
py> print bs
\
py> print repr(bs)
'\\'
This is a SINGLE character, only one backslash. repr() has to use two
backslashes and quotes around, but that's how repr works.
py> wrong = 'C:\abcde\fgh\ijklm\no'
py> print wrong
C:bcde♀gh\ijklm
o
py> print len(wrong)
18
py> good = 'C:\\abcde\\fgh\\ijklm\\no'
py> print good
C:\abcde\fgh\ijklm\no
py> print len(good)
21
Another way is to use a raw string. A raw string supresses the special
meaning of \ inside a string literal, and is indicated by a lowercase r
before the opening quote:
py> raw = r'C:\abcde\fgh\ijklm\no'
py> print raw
C:\abcde\fgh\ijklm\no
py> print len(raw)
21
Going back to your example:
> Because in my script I'm echoing the list to mount lists into lists,
> like:>>> list1 = ['name', 'test']
>>> list2 = ['path', 'c:\some\path']
This is wrong, and you already should know hot to write it: either
list2 = ['path', 'c:\\some\\path']
or
list2 = ['path', r'c:\some\path']
> Is it possible to print "list" without the doubled backslash?
print list2 will always print it using the doubled backslashes (and [ ]
around it).
Print each value individually:
py> for item in list2:
... print item
...
path
c:\some\path
Or tell us exactly what output you want, and we'll try to help more.
The important thing to remember is that '\\' is the way to *show* or
*represent* a single backslash in a string.
--
Gabriel Genellina
More information about the Python-list
mailing list