在python中使用反斜杠(不要转义) [英] using backslash in python (not to escape)
问题描述
import os
path= os.getcwd()
final= path +'\xulrunner.exe ' + path + '\application.ini'
print final
我想要输出:
c:\python25\xulrunner.exec:\python25\application.ini
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
无效的 \x 转义
如何将 '\' 用作 '\' 而不是转义符?
How can i use a '\' as a '\' and not an escape?
推荐答案
要直接回答您的问题,请将 r
放在字符串前面.
To answer your question directly, put r
in front of the string.
final= path + r'\xulrunner.exe ' + path + r'\application.ini'
但更好的解决方案是 os.path.join
:
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)
我会提到您可以在文件路径中使用正斜杠,Python 会根据需要自动将它们转换为正确的分隔符(Windows 上的反斜杠).所以
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'
应该可以.但最好还是使用 os.path.join
,因为这样可以清楚地表明您要做什么.
should work. But it's still preferable to use os.path.join
because that makes it clear what you're trying to do.
这篇关于在python中使用反斜杠(不要转义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!