1

I want to convert a string, which contains a file path, to a raw string, so the '\' characters are not considered escapes.

folderList = os.listdir(folderPath)
# folderList is a list of files, path = folderPath + (element of folderList)

So if I'm using something like this in Python 3, can I convert path to a raw string? I've tried using the encode method for strings, but that does not work. Also, I am not looking for solutions to replace the string '\' with '\'. I feel this process would take too long for how many paths I would have to process. So are there any simple conversions to convert path into a raw string?

WorldDominator
  • 141
  • 1
  • 5
  • 18
  • 2
    `path = r'c:\Users'` didn't work? – Ozgur Vatansever Feb 22 '15 at 22:40
  • Above comment should work: "Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the 'ur' syntax is not supported." from https://docs.python.org/3/reference/lexical_analysis.html – Francesco Gramano Feb 22 '15 at 22:43
  • I'm sorry I guess I made it unclear, that is not the answer I was looking for. I'm not defining the path myself I posted an example path. I want to convert the variable path to a raw string. I have a list of files that I'm going to be processing. – WorldDominator Feb 22 '15 at 22:50
  • @WorldDominator _" I'm not defining the path myself"_ Where and how is it being defined? – John1024 Feb 22 '15 at 23:04
  • 2
    You still haven't shown where the path is coming from. If you're reading it from a file or user input or something, none of this should be necessary. It should already work. – user2357112 Feb 22 '15 at 23:26

2 Answers2

1

As per the Python 3 documentation:

Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.

So in your case, path = r'c:\Users' should suffice.

If the data is already stored in a variable then it's important to realise that it already is a raw string. The \ character is used only to help you represent escaped characters in string literals. So;

>>> r'c:\Users' == 'c:\\Users'
True

From what you describe, therefore, you don't have anything to do.

dsclose
  • 556
  • 5
  • 15
-1

Yes there is a simple solution to this, you can try using path = r'c:\Users' or you can also use path = 'c:\\Users' whichever you feel like

ZdaR
  • 22,343
  • 7
  • 66
  • 87