wisecrack
wisecrack

Reputation: 335

Replacing "/" with "\" doesn't work

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

Upvotes: 0

Views: 158

Answers (3)

Abhishek Kashyap
Abhishek Kashyap

Reputation: 3638

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('/','\\')

Upvotes: 0

Sean McMillan
Sean McMillan

Reputation: 341

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

replaced_str = str.replace('/', '\\')

Upvotes: 2

Moses Koledoye
Moses Koledoye

Reputation: 78546

'/' 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.

Upvotes: 8

Related Questions