0

I am using replace string method in Python and I am finding something that I cannot understand.

Changing the way that a folder is written in python to windows notation, I find that replace method will change this double / for a double \ instead of just one \ as intended.

folder_im_wdows = folder_im_wdows.replace("//","\\")

But the most impressive, is that when I try a workaround doing the next

folder_im_wdows = folder_im_wdows.replace("//",chr(92))

Python does the same...

The original variable is: //xxxxx//xxxx//xxxx//xxxx//xxx//xxxxx And I want to get -> \xxx\x\x\x

What's happening with replace method?

3
  • 2
    It is working; you are confusing the string representation with the string itself. Try print(folder_im_wdows) to view the contents. Commented Nov 10, 2017 at 14:30
  • Also, are you sure you need to convert the paths? Commented Nov 10, 2017 at 15:04
  • @Luis B. Salgado Benitez : please accept an answer if your issues are solved. Commented Nov 17, 2017 at 14:55

2 Answers 2

3

This is because python's CLI escapes backslashes.

Example from python's CLI:

>>> str = "abc//def//fgh"
>>> str.replace("//", "\\")
'abc\\def\\fgh'
>>> print(str.replace("//", "\\"))
abc\def\fgh
>>>

Also, you should need to use \\ and not only \, because you need to escape the backslash character, well, I do.

Sign up to request clarification or add additional context in comments.

4 Comments

It's not the CLI; it's the implementation of str.__repr__.
@chepner: I don't understand. str.__repr__() -> "'abc\\\\def\\\\fgh'", print(str) -> abc\def\fgh
Because the CLI is then calling str.__repr__ on the output of the explicit call to str.__repr__.
Oh, I see. Thanks for the details
0

Use os.path for working with path names:

import os

os.path.normpath('C:/Users/Bob/My Documents')

os.path.abspath would do the job too (it uses os.path.normpath)

Note: requires host to be windows, if that's not the case you can use ntpath.normpath directly

https://docs.python.org/library/os.path.html#os.path.normpath

Avoid regexes, replaces and all that. You're going to get it wrong in some subtle way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.