Home > database >  Python - Error in String literal str.replace
Python - Error in String literal str.replace

Time:09-24

I have attempted to replace a string in a column with either of the two commands below. For both of them, I am getting the "SyntaxError: EOL while scanning string literal" error. Please help/guide. Thanks.

df['filename'] = df['filename'].str.replace("H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\","", inplace=True)
df["filename"] = df["filename"].apply(lambda x: x.replace("H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\", ""))  

CodePudding user response:

\ denotes escape sequence in python, if you mean literal \ then use \\, i.e. replace

"H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\"

using

"H:\\May2017\\hb_ymvid\\HB_ED_S\\Pictures1\\05cropped_PC\\"

and so on

CodePudding user response:

Use str.replace with regex=False because you don't use a regex:

root_dir = 'H:\\May2017\\hb_ymvid\\HB_ED_S\\Pictures1\\05cropped_PC\\'

df['filename'] = df['filename'].str.replace(root_dir, '', regex=False)

Output:

>>> df
      filename
0  image01.png
1  image02.png

I used this sample:

df = pd.DataFrame({'filename': [r"H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\image01.png",
                                r"H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05cropped_PC\image02.png"]})
print(df)

# Output
                                            filename
0  H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05croppe...
1  H:\May2017\hb_ymvid\HB_ED_S\Pictures1\05croppe...
  • Related