0

I want to replace "'" with "\'" inside the word "O'Fallon". But when I use the following code:

City="O'Fallon"
City.replace("'","\'")

I get "O'Fallon" as the output and when use this code:

City="O'Fallon"
City.replace("'","\\'")

I get "O\\'Fallon" as the output. Could you please help me on this?

4
  • The double slash is normal behaviour. Try print City.replace("'", "\\'"). Commented Apr 28, 2015 at 17:14
  • I think you're looking for something like repr(City) or pipes.quote(City) (or shlex.quote() on Python >= 3.3), depending on what environment you want to escape your string for. Commented Apr 28, 2015 at 17:16
  • @MartijnPieters obviously, that's why the OP thinks their second attempt doesn't work. But my point was: If they have need to escape single quotes, they probably need to escape strings that are going to be interpreted by a specific parser. Maybe Python, maybe a shell, who knows. Sot hey should use a function that properly escapes every character with special meaning in the target environment, and not just replace single quotes. Commented Apr 28, 2015 at 17:25
  • @LukasGraf: right, I see what you mean. I made a similar comment below, sensing that they are using this in a SQL query somewhere. At which point you'd ask the database driver to do the escaping.. Commented Apr 28, 2015 at 17:30

1 Answer 1

2

That's just the representation shown in the console.

If you print it, you'll see it's all fine.

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

4 Comments

I don't want to print it, I want to add it as a part of a query.
Doesn't matter. It's fine.
@user2079550: the print shows you that the value contains just the one backslash, not two. Another way to see this is to use result[1:3], len(result[1:3]), which will produce ("\\'", 2). You can use it as part of a query.
@user2079550: however, if this is part of a SQL query, then don't try and escape the values yourself. Leave that to the database driver, use SQL parameters, not string concatenation or interpolation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.