Reputation: 950
How would I add the "\"
char to a string?
For instance, if I have "testme"
and I do
"testme"+"\"
I would get an error.
What is a "pythonic" approach for adding a "\"
before each paren in a string?
For instance to go from "(hi)" to "\(hi\)"
My current approach is to iterate through each char and try to append a "\"
which I feel isn't that "pythonic"
Upvotes: 0
Views: 367
Reputation: 208485
Backslashes are used for escaping various characters, so to include a literal backslash in your string you need to use "\\"
, for example:
>>> print "testme" + "\\"
testme\
So to add a backslash before each paren in a string you could use the following:
s = s.replace('(', '\\(').replace(')', '\\)')
Or with regular expressions:
import re
s = re.sub(r'([()])', r'\\\1', s)
Note that you can also use a raw string literal by adding a the letter r
before the opening quote, this makes it so that backslash is interpreted literally and no escaping is done. So r'foo\bar'
would be the same as 'foo\\bar'
. So you could rewrite the first approach like the following:
s = s.replace('(', r'\(').replace(')', r'\)')
Note that even in raw string literals you can use a backslash to escape the quotation mark used for the string literal, so r'we\'re'
is the same as 'we\'re'
or "we're"
. This is why raw string literals don't work well when you want the final character to be a backslash, for example r'testme\'
(this will be a syntax error because the string literal is never closed).
Upvotes: 9
Reputation: 250961
>>> import re
>>> strs = "(hi)"
>>> re.sub(r'([()])',r'\\\g<0>',strs)
'\\(hi\\)'
"\"
is invalid because you're escaping the closing quote here, so python will raise EOF error.
So you must escape the \
first using another \
:
>>> "\\"
'\\'
>>> "\"
File "<ipython-input-23-bdc6fd40f381>", line 1
"\"
^
SyntaxError: EOL while scanning string literal
>>>
Upvotes: 0