1

I have a string This is a Test and a passed parameter s. How can I escape all s-characters of that first string?

It should result in Thi\s i\s a Te\sT

I tried it like this:

rstr = rstr.replace(esc, r"\\" + esc) 

But it will result in \\ before each s

1
  • Actually, use simply "\\" instead of r"\\". Making it a raw string means that \\ really does become \\, but you still can't end a string with a single backslash. Commented Jan 21, 2014 at 12:34

1 Answer 1

2

r'\\' produces a literal double backslash:

>>> r'\\' '\\\\' 

Don't use a raw string here, just use '\\':

>>> 'This is a Test'.replace('s', '\\s') 'Thi\\s i\\s a Te\\st' 

Don't confuse the Python representation with the value. To make debugging and round-tripping easy, the Python interpreter uses the repr() function to echo back results.

The repr() of a string uses Python literal notation, including escaping any backslashes:

>>> r'\s' '\\s' >>> len(r'\s') 2 >>> print r'\s' \s 

The actual value contains just one backslash, but because a backslash can start characters with special meanings, such as \n (a newline), or \x00 (a null byte), they are represented escaped so that you can paste the value directly back into the interpreter.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.