-2

I wrote a function in Python that takes a file path as an argument. Ideally, I would like to 'concatenate' an r at the beginning to escape the characters, and turn it into r"C:\User\name\location".

I am having trouble finding any solutions- are there any modules to help with this?

shuaf98
  • 55
  • 1
  • 1
  • 5
  • 2
    Raw strings are just for literals in code, they aren't part of the string data itself. – Barmar Jul 08 '21 at 17:16
  • So you don't need to do anything if the strings are data. – Barmar Jul 08 '21 at 17:17
  • The duplicate has some confusing answers; but several of the highest-voted tell you what @Barmar is also communicating above. – tripleee Jul 08 '21 at 17:32
  • If you were asking because you want to call a function with a string without having to put `r` in front of it, e.g. `func("c:\Users")` the answer is it can't be done. – Mark Ransom Jul 08 '21 at 17:36
  • I actually tried every solution in that thread already, none of them seem to work. str.encode(unicode-escape).decode() solution works for regular strings, but isn't working for the file path. Still getting the error "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (, line 3)". – shuaf98 Jul 08 '21 at 19:04

1 Answers1

0

You do not require any modifications to the function at all.

def f(path):
    ...
    ...

f(r"C:\User\name\location")

The "r" you referred to would be used to form the string that you pass to the function. A string is a string, it does not matter how you form it, but Python offers you different ways of doing so e.g.:

f("C:\\User\\name\\location")

By the time the function is passed the string, the string has already been formed. It now makes no difference how it was formed, only that it has all of the correct characters in all the correct places!

Pippet39
  • 127
  • 4
  • Thanks, however unless I am not understanding, this doesn't solve the problem. I specifically want the path to be read in the format posted. I want the function to pass a path which was taken by copying the path from file explorer, and don't want the user to have to manually place the 'r' before hand. – shuaf98 Jul 08 '21 at 19:08
  • okay, I see. I think the trouble is that if you create a string like "C:\an\example", the information you're trying to preserve will already be erased by the time the function sees the string, since any valid escape characters will already be replaced. There might be a reliable way to undo this escaping inside the function, but I'm not sure if this will work in all cases. – Pippet39 Jul 08 '21 at 20:33