3

This has probably answered somewhere at sometime but the titles I have seen don't connect so here it goes. I have seen python commands that read os.listdir(r".\bootstrapper"). What is the 'r' doing?

Cheers...

5 Answers 5

6

it prevents the Python interpreter from attaching any special meanings to special characters in the string (such as the backslash), and just interpret it as is (i.e., in its "raw" form). This is one way you can "escape" special characters in strings you use.

You'll often see raw strings in path specifications. Let's say the path contains a directory that starts with t, e.g., c:\tests\data.csv, so you'd not want \t to be interpreted as a tab, hence use the r modifier.

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

3 Comments

Slightly nitpicky, but note that Python doesn't attach special meaning to the string, but to the backslashes (escape sequences) within the string literal.
@benhoyt So noted, I'll update my explanation to be more precise - thanks
@user466740 Just a friendly note, if this solved your problem, please consider accepting this answer by clicking on the checkmark next to my answer. It'll mark this problem as solved, and reward both of us with some rep points - thanks.
3

r marks raw input. This means that the normal escape characters within the string are ignored (like \ )

Comments

2

It's a raw string which removes the special nature of backslash.

Reference.

1 Comment

Good idea to reference -- but you've linked to the re module rather than the documentation about string literals (including raw strings).
1

It makes it a raw string. In other words, backslashes will be preserved. '\n' is interpreted as a new-line, but r'\n' is interpreted as the literal characters '\' and 'n'.

Also note that occasionally you'll see u'string' if you're using python2.x code. This implies that the string should be interpreted as a unicode string. (in python 3.x, all strings are interpreted as unicode)

1 Comment

Python 3.3 will allow the u unicode indicator (python.org/dev/peps/pep-0414), making one less thing to worry about when porting 2 to 3.
1

r means raw input. If a string is marked as r, then the meaning of any special character whithin the string will be ignored, the most frequently situation will be the backslash.

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.