printing backslash

Fredrik Lundh fredrik at pythonware.com
Wed Jun 7 12:58:59 EDT 2006


micklee74 at hotmail.com wrote:

> i want to print something like this
> 
> |\|
> 
> first i tried it as string
> 
> a = "|\|"
> 
> it prints ok
> 
> but when i put it to a list
> 
> a = ["|\|"]
> 
> it gives me '|\\|'.

if you want to print "|\|", why are you printing the list?

> there are 2 back slashes...i only want one..

there's only one in the string; the other one is added by the list-
to-string conversion.  if you print the *list item* instead, only one 
backslash is printed.

the correct way to add a single backslash to a string is to write *two* 
backslashes in the string literal, like this:

     "|\\|"

this results in a 3-character string, which is printed as |\|, but is 
echoed back as '|\\|' by the repr() operator (which is used by the 
interactive prompt, and the list-to-string conversion, among others).

     >>> s = "|\\|"
     >>> s # implicit repr
     '|\\|'
     >>> print s
     |\|
     >>> len(s)
     3
     >>> print repr(s)
     '|\\|'
     >>> print str(s)
     |\|

     >>> x = [s]
     >>> x # implicit repr
     ['|\\|']
     >>> print x[0]
     |\|

</F>




More information about the Python-list mailing list