Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing backtick in pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading