trouble using "\" as a string

Dan Bishop danb_83 at yahoo.com
Sun Aug 20 02:04:51 EDT 2006


OriginalBrownster wrote:
> Hi there...
>
> I'm still pretty new to turbogears. but i have gotten pretty familiar
> with it
>
> i'm just trying to clear something up, i'm having a difficult time
> using \ when declaring a string expression
>
> such as tempname="\"..it says that the line is single qouted.
>
> i want this because using python I am pulling in filenames from a
> mac..thus they are "/" in the pathways..and i want to .split it at the
> "/" to obtain the filename at the end...but its proving diffucult with
> this obstacle in the way.
>
> Why is this happening??

In Python (and many other programming languages), the backslash is the
"escape character".  That is, special characters are indicated by
sequences that start with a backslash.

>>> print 'Line 1\nLine 2' # \n = newline
Line 1
Line 2
>>> print 'tab\tseparated\ttext' # \t = tab
tab     separated       text
>>> print 'This parrot is dead\b\b\b\balive!'  # \b = backspace
This parrot is alive!
>>> print 'The ASCII code for \x41 is 0x41.'
The ASCII code for A is 0x41.
>>> 'It\'s necessary to escape a quote that\'s within the same type of quote.'
"It's necessary to escape a quote that's within the same type of
quote."

An escape sequence is always considered a single character.  (As
mentioned earlier, you can verify this with the len function.)  Thus,
your "\" gets parsed as:

" = opening quote of string
\" = double quotation mark (escaped)
end of line = error, because no closing quote was found

If you want a backslash, you have to escape *it* with a backslash: "\\"




More information about the Python-list mailing list