Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unknown python expression filename=r'/path/to/file'

Tags:

python

string

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!

like image 977
Lisa Avatar asked Sep 26 '13 17:09

Lisa


People also ask

What is R in file path in Python?

An 'r' preceding a string denotes a raw, (almost) un-escaped string. The escape character is backslash, that is why a normal string will not work as a Windows path string.

How do you add R to a PATH variable in Python?

Just use path = variable . The point of the r'...' notation is for writing raw string literals; it changes the rules for character escaping inside of the quotes.

How do I open a file in a different directory in Python?

Use open() to open a file in a different directory Join path with filename into a path to filename from the current directory. Call open(file) with file as the resultant path to filename to open filename from the current directory. Hello, World!

How do you make a string variable raw in Python?

In Python, when you prefix a string with the letter r or R such as r'...' and R'...' , that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes ( \ ) as literal characters.


1 Answers

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.

like image 161
Maciej Gol Avatar answered Oct 13 '22 00:10

Maciej Gol