0

I have a string stored in a variable like so

s = '(copy('

and I want my output to be like this

out = '\(copy\('

I have tried to do the following

s = '(copy('
r = '('

# Option 1
# out = s.replace(r, '\' + r, s.count(r))

# Option 2
out = s.replace(r, r'\' + r, s.count(r))

But both options are giving me SyntaxError: EOL while scanning string literal which is understandable because it is telling me that a string somewhere isn't closed or some part in the string isn't escaped.

But of course, if I escape the backlash with something like

s.replace(r, '\\' + r, s.count(r))

It will give me output like this \\(copy\\( yet what I want is \(copy\(.

Any idea on how I could go about this. Thank you in advance.

kellymandem
  • 1,709
  • 3
  • 17
  • 27
  • 1
    `s.replace(r, '\\' + r)` is correct. – Aran-Fey Mar 08 '19 at 17:07
  • 1
    `s = "(count("; r = "("; print(s.replace(r, "\\"+r, s.count(r)))` prints `\(count\(` on my machine. How are you getting your output? Note that doing `>>> s` in a REPL will not always give the same output as doing `>>> print(s)`. The former may render additional slashes, and this is by design. – Kevin Mar 08 '19 at 17:09
  • @Kevin I understand now, it is because I was outputting directly in a REPL and not using print. Thank you – kellymandem Mar 08 '19 at 17:14

0 Answers0