Skip to content Skip to sidebar Skip to footer

Unknown Python Expression Filename=r'/path/to/file'

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/o

Solution 1:

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.

Solution 2:

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

Solution 3:

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.

Post a Comment for "Unknown Python Expression Filename=r'/path/to/file'"