[HowTo] handle \ (backslash) and " (double quotes) in strings

Created by RaiMan
Keywords:
Last updated by:
RaiMan

generally, if you have a string like

"some text containing \ (backslash) and " (apostrophes, double quotes)"

these two characters have to be escaped with a backslash (a \ put before the character):

"some text containing \\ (backslash) and \" (apostrophes, double quotes)"

There is an alternative, that does not need escaping and takes a \ and " literally:
raw string: put into single quotes : r'some text containing \ (backslash) and " (apostrophes, double quotes)'

This might be the easier version, when building a command that you want to run from a Sikuli script:

import os
os.system(r'"c:\Program Files\Some Command" "some parameter"')

so the string
"c:\Program Files\Some Command" "some parameter"
is given to the command processor as needed to work as expected

The first drawback: a \n will not be translated to a new line character (and the other \x).
If you need this, you have to concatenate:
text = r'"c:\Program Files\Some Command" "some parameter"' + "\n" + r'"some more text"'

The second drawback: a single \ cannot be the last character in a raw string
So again you could use concatenation:
r'c:\SomeFolder' + "\\"
or
r'c:\SomeFolder\\'[:-1]
which looks like Python is laughing at us - but works ;-)