0

I'm getting error "error: bad escape \d at position 1" when working on date formatting. I have to convert from format 11/13.2015 to 11/13/2015. I'm replacing using a regex and converting to a date-time format. Below is the code:

import pandas as pd
import datetime as dt
File = pd.read_excel("dotcharacter.xlsx")
Final_file = File["Date"].replace("[\d{2}\/\d{2}\.\d{4}]","[\d{2}\/\d{2}\/\d{4}]",regex=True)
Final_file["Date"] = pd.to_datetime(Final_file["Date"]).dt.strftime("%m/%d/%Y")
Final_file.to_excel("modified_file.xlsx")

Simple, File.replace(".","/") will do the trick. However, how can I test using a regex? I'm new to Python. So, I am trying something different.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nani
  • 1
  • 1
  • 1
    You need a double backslash. One to escape the backslash, and one to be a part of `\d`. So it's `\\d`. – Nick ODell Jul 11 '22 at 16:32
  • Use a raw string for regular expressions. – Barmar Jul 11 '22 at 16:35
  • Should I use \\d everywhere replacing \d - @Nick – Nani Jul 11 '22 at 16:42
  • Barmar's suggestion, of using a raw string, like `r'...'` is probably easier to read. But both ways will work. – Nick ODell Jul 11 '22 at 16:43
  • @NickODell - Tried the code "Final_file = File.replace("[r"\d{2}\/\d{2}\.\d{4}"]","[r"\d{2}\/\d{2}\/\d{4}"]",regex=True)" but I'm getting new error "SyntaxError: unexpected character after line continuation character". I don't see space anywhere in the code. Please help. – Nani Jul 11 '22 at 16:52
  • 1
    `"[r"` This isn't the right way to make a raw string. The r goes before the quote. And another quote will end the raw string early. – Nick ODell Jul 11 '22 at 16:58
  • Thanks @Nick. I understood raw string representation is r'...' and r"...". But, it is not working in this case. I don't know why. Could you please, help me out? – Nani Jul 11 '22 at 17:21
  • Guys, can anyone please, help me on the below line of code. I'm getting error when I'm trying to execute: `New_File = File.replace(r"\\d{2}\/\d{2}\.\d{4}",r"\d{2}\/\d{2}\/\d{4}",regex=True)`. Error is KeyError: '\\d' and error: bad escape \d at position 0 – Nani Jul 12 '22 at 04:07

0 Answers0