Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using backslash in python (not to escape)

import os path= os.getcwd() final= path +'\xulrunner.exe ' + path + '\application.ini' print final 

I want the out put:

c:\python25\xulrunner.exe c:\python25\application.ini

I don't want backslash to work as string, i mean don't want it to escape or do anything special. But i get an error

Invalid \x escape

How can i use a '\' as a '\' and not an escape?

like image 204
esafwan Avatar asked Aug 01 '10 02:08

esafwan


People also ask

Do you need to escape backslash in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do you keep a backslash in Python?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do I stop characters from escaping Python?

For turning a normal string into a raw string, prefix the string (before the quote) with an r or R. This is the method of choice for overcoming this escape sequence problem.

Why do some backslashes need to be escaped?

Answer. When a string is double quoted, it is processed by the compiler and again at run-time. Since a backslash (\) is removed whenever the string is processed, the double-quoted string needs double backslashes so that there is one left in the string at run time to escape a "special character".


2 Answers

To answer your question directly, put r in front of the string.

final= path + r'\xulrunner.exe ' + path + r'\application.ini' 

But a better solution would be os.path.join:

final = os.path.join(path, 'xulrunner.exe') + ' ' + \          os.path.join(path, 'application.ini') 

(the backslash there is escaping a newline, but you could put the whole thing on one line if you want)

I will mention that you can use forward slashes in file paths, and Python will automatically convert them to the correct separator (backslash on Windows) as necessary. So

final = path + '/xulrunner.exe ' + path + '/application.ini' 

should work. But it's still preferable to use os.path.join because that makes it clear what you're trying to do.

like image 106
David Z Avatar answered Sep 24 '22 02:09

David Z


You can escape the slash. Use \\ and you get just one slash.

like image 26
avacariu Avatar answered Sep 23 '22 02:09

avacariu