15
votes

I found this potentially very useful python script, but came across these expressions which I've never seen before:

inputfilename = r'/path/to/infile'
outputfilename = r'/path/to/outfile'

I can't find a way to search for it. what does the r'...' do?

Thanks for your help!

3
This is a "raw string," see the documentation. Often used to be able to write special characters (e.g. ``) without escaping. - bbayles
r is a raw string literal which enables you to forget about the escape sequences! stackoverflow.com/questions/3517802/python-raw-literal-string - Vivek
It doesn't make a difference in this case, but if the path had backslashes you would want to include the r - beroe
Thanks everyone! And yes, the posted link also answers my question. - Lisa

3 Answers

13
votes

The r'..' string modifier causes the '..' string to be interpreted literally. That means, r'My\Path\Without\Escaping' will evaluate to 'My\Path\Without\Escaping' - without causing the backslash to escape characters. The prior is equivalent to 'My\\Path\\Without\\Escaping' string, but without the raw modifier.

Note: The string cannot end with an odd number of backslashes, i.e r'Bad\String\Example\' is not a correct string.

3
votes

It's called raw string literal.

According to Python String literals documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

...

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C

2
votes

It just means raw string in Python. Meaning that whatever is inside the string, is the string. For example, if you wanted to add slashes:

string1 = "happy\/cheese"

You would need to add \ in front of the slash since its an escaping character. For example, \n means a new line.

If you keep the string raw, it makes sure that whatever is in the string is not interpreted a special way. for example if you wrote string2 = r"\n", it would just give you "\n" as you string, and not a new line.

You can learn more about them, from here.

Now, this is done in your case, because file paths have a lot of slashes, and we'd like to avoid having to put in so many backslashes.