Search code examples
pythonstringreplacebackslash

Python replace '\' with '/' where '\' is followed by 't'


How to replace all backslashes with slashes in a string where at least one backslash is immediately followed by the character 't'? I use replace('\\', '/'), but the '\t' is interpreted as tab and it is not replaced.

Example:

'D:\myfiles\test'.replace('\\','/')

Output:

'D:/myfiles\test'

Similar things happen with combinations like '\f', '\n', etc.


Solution

  • \t , \f, \n, etc. are escape sequences. So, whenever you need to use them in a string, you need to use \\ instead of \.

    In your case, you should do

    'D:\\myfiles\\test'.replace('\\','/')