Home > OS >  Why Python replaces double backslashes with one and how can I keep it double
Why Python replaces double backslashes with one and how can I keep it double

Time:11-12

I am new to Python and I have difficulties with the above-mentioned problem.

I have a loop here that gives me paths of all folders that I need

    for i in folder_names:
        print(str("pd.read_csv('C:\\Users\\User\\Desktop\\Python\\4_Мини-проект\\data\\2020-12-03\\")   i   str("\\data.csv')"))

The problem is that for some reason I lose my double backslashes in the result which is:

pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Alexey_Smirnov\data.csv')
pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Anton_Petrov\data.csv')
pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Kirill_Petrov\data.csv')
pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Petr_Fedorov\data.csv')
pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Vasiliy_Ivanov\data.csv')
pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03\Vasiliy_Petrov\data.csv')

I tried the "replace" method, but it didn't work

.replace('\', '\\')

I would be grateful for the help and an explanation of the reason why this happens.

CodePudding user response:

\ is know as an escape character. In simple terms when you type a \ in your code, the \ and the proceeding character will act as one single character, such as \n or \t.

When you want to type a backslash in your code, not as an escape character, then you must type \\. The first backslash is the escape character, and the second one is the proceeding character.

This means that if you want to have two regular backslashes in your code, you must type \\\\.

CodePudding user response:

You can use the raw string. You just need to put a "r" for the string. So your code look like this:

    for i in folder_names:
        print(str(r"pd.read_csv('C:\Users\User\Desktop\Python\4_Мини-проект\data\2020-12-03")   "\\"   i   str(r"\data.csv')"))

The " "\\" " is because the raw string can't be used on the end of the sting otherwise your " will be printed and you get an error because your string isn't closed.

  • Related