using backslash in python (not to escape)

自闭症网瘾萝莉.ら 提交于 2019-11-26 02:38:47

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3380484/using-backslash-in-python-not-to-escape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!