I have the following data frame:
my_places = ['Bernardo O\'Higgins', 'Bernardo O`Higgins', 'Bernardo O\"Higgins']
adf = pd.DataFrame({'my_places':my_places})
adf
my_places
0 Bernardo O'Higgins
1 Bernardo O`Higgins
2 Bernardo O"Higgins
And I try to replace the characters ',` and " with ''. So I tried this:
adf['my_places_check'] = adf['my_places'].replace(''|"|`','')
But I get an error:
SyntaxError: EOL while scanning string literal
I think I have to 'escape' the special characters, so I tried this:
adf['my_places_check'] = adf['my_places'].replace('\'|\"|\`','')
But it returns this:
my_places my_places_check
0 Bernardo O'Higgins Bernardo O'Higgins
1 Bernardo O`Higgins Bernardo O`Higgins
2 Bernardo O"Higgins Bernardo O"Higgins
And I expected:
my_places my_places_check
0 Bernardo O'Higgins Bernardo OHiggins
1 Bernardo O`Higgins Bernardo OHiggins
2 Bernardo O"Higgins Bernardo OHiggins
Any help will be greatly appreciated.
CodePudding user response:
You need to use
adf['my_places_check'] = adf['my_places'].replace("""["`']""", '', regex=True)
Details:
"""["`']"""
- a regex that is["`']
''
- is the replacement (an empty string)regex=True
- make sure the pattern is parsed as a regex
If you use "
or '
as a string literal delimiter, you will need to escape the corresponding literal char inside the string literal, so using a triple-quoted string literal is a more readable solution.