Gonzalo Martín
Gonzalo Martín

Reputation: 23

Why is str.replace("\\","/") not working?

I wanted to replace them so python can open the file in order to split it, but it doesn't work cause it's giving me the error:

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I'm relatively new to python, but I've seen a lot of sites where they say that this solution works and there's no more code, therefore idk what is wrong with this.

(My goal is to use the separated file to write it on an excel)

def separator(filepath):
    files = filepath.replace("\\", "/")
    f=open(files, "r")
    txt = f.read().split("\n")
    f.close()
    print(txt)

separator("C:\Users\Gonza\Coding\Heads or Tails\HeadsTails.txt")

SOLUTION: Ok so I solved it and today I figured out it was a good idea to leave this solution here, so what I did was changing:

files = filepath.replace("\\", "/")

Into this:

files = repr(filepath).replace("\\\\","/").replace("\'","")

What repr() does is transforming the string into a representable version of itself (which I think is the same as r'), with that done .replace("\\","/") works perfect but repr() also adds quotation marks to it, so I took them out with another .replace("\'", "") that way the path is ready to work.

NOTES: I wanted to mention that I only did this cause I wanted to input the path, I'm also sure there's an easier way to do this with the os.path module.

Upvotes: 0

Views: 93

Answers (2)

Talon
Talon

Reputation: 1884

Your function call is

separator("C:\Users\Gonza\Coding\Heads or Tails\HeadsTails.txt")

The backslashes there are not escaped, so there isn't really a backslash in there.

When you manually input that, you can write an r in front of the string

separator(r"C:\Users\Gonza\Coding\Heads or Tails\HeadsTails.txt")

Which will not apply backslash-escaping.

Upvotes: 2

Vizzyy
Vizzyy

Reputation: 540

Use raw string for input: https://www.askpython.com/python/string/python-raw-strings

separator(r"C:\Users\Gonza\Coding\Heads or Tails\HeadsTails.txt")

Note the "r" before the string

If I'm understanding your issue correctly, at least when I put it into my IDE, the input string is escaping the slashes instead of keeping them as is. "\" Escapes the next character in a regular string.

Upvotes: 1

Related Questions