0

I am trying to replace / with \ as below, but it doesn't work, why is that?

str = "images/companyPkg/Pkg/nib64/"
replaced_str = str.replace('//','\\')
print replaced_str
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
wisecrack
  • 315
  • 2
  • 12

3 Answers3

8

'/' does not need to be doubled. '\' is doubled because strings cannot end with '\':

s = "images/companyPkg/Pkg/nib64/"
replaced_str = s.replace('/','\\')

Don't assign anything to the name str, str is a builtin (class for strings) in Python. Making an assignment will make the builtin name unusable later on in your code. You don't want that.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

You don't need to escape the / in python just the \ so the following line should do the trick:

replaced_str = str.replace('/', '\\')
Sean McMillan
  • 341
  • 2
  • 6
0

You should double the back slash \ because it is the escape character and used to provide a special meaning to the certain characters as for example n is simple 'n' but \n is a new line, but forward slash / is a simple character so you don't need to double it.

You should write replaced_str = str.replace('/','\\')

Abhishek Kashyap
  • 3,332
  • 2
  • 18
  • 20