RRRRR
RRRRR

Reputation: 13

python replace backslash and single quote

I have the this code:

'Tokyo\'s'.replace(r'\"', '"').replace(r"\'", ''')

I already looked at some of the old StackOverflow topics regarding this issue but couldn't figure out.

I still get the same result back Tokyo\'s

result looking for is Tokyo's

I am trying to convert them to XML escaped char

https://www.advancedinstaller.com/user-guide/xml-escaped-chars.html

also tried using escape("'") which gives me \' back.

Your suggestions would be appreciated!

Upvotes: 0

Views: 866

Answers (3)

abc
abc

Reputation: 1004

Get rid of the escape \:

'Tokyo\'s'.replace('"', '"').replace("'", ''')

This will return 'Tokyo's'

When using r"\'" as the target to replace, it will look for the pattern \' exactly. That pattern doesn't exist in your original string Tokyo's.

Note: The original string is not Tokyo\'s, because the \' in this string is escaping '

Upvotes: 3

Terry Spotts
Terry Spotts

Reputation: 4035

You may gain more flexibility here and cleaner code using translate():

table = str.maketrans({'"': '"',
                       "'": '''
                       }
                      )

print('Tokyo\'s'.translate(table))

Ouput:

Tokyo's

Upvotes: 0

Błotosmętek
Błotosmętek

Reputation: 12927

print('Tokyo\'s'.replace('"', '"').replace("'", '''))

should work, but in general, if you want characters replaced with HTML entities, see https://wiki.python.org/moin/EscapingHtml

Upvotes: 0

Related Questions