[Tutor] Raw string form variable

Peter Otten __peter__ at web.de
Sun May 5 10:34:49 CEST 2013


Ajin Abraham wrote:

> Please refer this paste: http://bpaste.net/show/vsTXLEjwTLrWjjnfmmKn/
> and suggest me the possible solutions.
> Regards,

Quoting the paste:

> i am executing these in Python 2.7 interpreter
> >>>import os
> >>> os.path.join(r'C:\win\apple.exe')
> #will returns me = 'C:\\win\\apple.exe'

os.path.join() is pointless if you have only one component. It is meant to 
*join* a directory with a basename, or multiple directory names etc.

The double backslashes are an artifact of the display mechanism built into 
the interactive interpreter that does the escaping on the fly. It is caused 
by an implicit call to the repr() function. Compare:

>>> path = r"c:\win\apple.exe"
>>> path
'c:\\win\\apple.exe'
>>> print repr(path)
'c:\\win\\apple.exe'
>>> print path
c:\win\apple.exe

> >>> path='c:\win\apple.exe'
> #here for example i assign the path. but in my case value is assigned to 
my variable after a file read operation.
> >>> path
> 'c:\\win\x07pple.exe'
> # i know '\a' is encountered here.

Certain combinations of the backslash have a special meaning, but only in 
Python source code. \n stands for newline, \t for the tab and \a for alarm 
(beep), and \\ for the backslash.

> #but i need it as 'C:\\win\\apple.exe'
> How can i convert the content of a variable to a raw string.
> 
> help me out
> 
> this is a solution but it didn't worked out: 
http://code.activestate.com/recipes/65211/

You are asking for the solution of a non-problem. Backslashes are only 
treated specially in string literals in Python source code. If you are 
reading filenames from a file


with open("mypaths.txt") as f:
    for line in f:
        path = line.strip()
        print path

The filenames will be taken as is. The only problem you may run into is 
filenames with non-ascii characters. If the encoding used in the file 
differs from that of the file system you should use

import codecs
encoding = ... # "UTF-8" or "ISO-8850-1" or whatever
with codecs.open("mypaths.txt, encoding=encoding) as f:
    ...
    



More information about the Tutor mailing list