0

I wrote a short script to turn the '\' in the path to '\\'

def useinR(address):
    address_list=address.split("\\")
    r_address="\\\\".join(address_list)
    print(r_address)

I need to add an "r" in front of the path to make sure it works well, as This Question mentioned

so when I use that script, I need to enter

useinR(r"F:\Study\UWA\CITS4009\w11_example\protein.txt")

instead of

useinR("F:\Study\UWA\CITS4009\w11_example\protein.txt")

How can we avoid enter the r before path?

I tried r+address , but in that case the "r" is in the string, so it doesn't work

Why I need to do this:

We cannot use file path like F:\abc.txt in RStudio

we need to enter F:\\abc.txt

Yiling Liu
  • 666
  • 1
  • 6
  • 21
  • 3
    ``address=address`` -this line is useless. – Psytho Oct 26 '18 at 12:24
  • Does [this Q&A](https://stackoverflow.com/q/2428117/9209546) help? – jpp Oct 26 '18 at 12:25
  • 3
    The whole function is useless. There's no reason to double the backslashes like that. – Aran-Fey Oct 26 '18 at 12:25
  • 1
    We actually don't have proper canonical for these kinds of questions, so if someone wants to post an answer that explains why converting existing strings to "raw strings" is nonsensical, that would be great. I recently looked through all the "raw string" questions I could find, and I couldn't find one with that kind of answer. The closest thing we have is [this unclear garbage](https://stackoverflow.com/questions/4415259/python-raw-strings). – Aran-Fey Oct 26 '18 at 12:26
  • sorry, I deleted that address=address. It was the remain code when I tried r+address – Yiling Liu Oct 26 '18 at 12:35
  • Why I wrote this is we cannot use path like F:\ abc.txt in R, we need to use F:\\ abc.txt – Yiling Liu Oct 26 '18 at 12:36
  • I'll just give you a short answer here: *"How can we avoid enter the r before path?"* We don't. Using the `r` is the correct solution. – Aran-Fey Oct 26 '18 at 12:53
  • Look into using the `os` package from the standard library. https://docs.python.org/3/library/os.html – David Hoffman Oct 26 '18 at 13:08

1 Answers1

0

The syntax r"string\with\slashes" indicates that the string literal should be treated as a raw string, which means that slashes do not denote unicode control sequences in the string.

If you want to pass string literals to your useinR function, you need to add the raw string prefix. The prefix can't be applied in front of a variable because it relates only to literals.

Bruce Collie
  • 435
  • 3
  • 8