1

Why does replacing backslashes with frontslashes like below does not work for the second backslash?:

x = 'O:\MAP\04_Operational Finance\Billing\Billings Reconciliation'.replace('\\', '/')
print(x)

Printing output is:

O:/MAP_Operational Finance/Billing/Billings Reconciliation
barciewicz
  • 3,511
  • 6
  • 32
  • 72
  • 4
    a backslash used in literals get treated as an escape character. It seems to treat `\04` as a special character. try using "raw" strings, where no such escaping occurs: `x = r'...'` – Felk Aug 10 '18 at 13:08
  • Hint: think carefully about why the code **doesn't** say `.replace('\', '/')`; then consider the implications for how to write `'O:\MAP\04_Operational Finance\Billing\Billings Reconciliation'` properly. – Karl Knechtel Aug 07 '22 at 02:13

3 Answers3

9

'\04' is a string literal and the escape sequence \04 in that literal already means something other than "backslash oh four". It's the escape sequence to write the byte x04 as part of the string. Your string never contained the characters "backslash oh four" to begin with. If you want to have backslashes in string literals without them being interpreted as escape sequences, you need to escape them:

'O:\\MAP\\04_Operational Finance\\Billing\\Billings Reconciliation'

Or use raw literals:

r'O:\MAP\04_Operational Finance\Billing\Billings Reconciliation'
deceze
  • 510,633
  • 85
  • 743
  • 889
1

Your string should use '\\' as it is not a raw string and backslashes need to be escaped. \0 is some kind of escape character I presume

x = 'O:\\MAP\\04_Operational Finance\\Billing\\Billings Reconciliation'.replace('\\', '/')

Or you could prefix your string with r: r'string' which denotes a raw string where you don't need to escape the backslashes

N Chauhan
  • 3,407
  • 2
  • 7
  • 21
1

Use r -> using backslash in python (not to escape)

x = r'O:\MAP\04_Operational Finance\Billing\Billings Reconciliation'.replace('\\', '/')
print(x)
O:/MAP/04_Operational Finance/Billing/Billings Reconciliation
keithpjolley
  • 2,089
  • 1
  • 17
  • 20