在python中使用反斜杠(不要转义)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3380484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:44:52  来源:igfitidea点击:

using backslash in python (not to escape)

pythonstringbackslash

提问by esafwan

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

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

无效的 \x 转义

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

我如何使用 '\' 作为 '\' 而不是转义符?

采纳答案by David Z

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

要直接回答您的问题,请放在r字符串前面。

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

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

但更好的解决方案是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

我将提到您可以在文件路径中使用正斜杠,并且 Python 会根据需要自动将它们转换为正确的分隔符(Windows 上的反斜杠)。所以

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

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

应该管用。但是使用它仍然更可取,os.path.join因为这可以清楚地表明您要做什么。

回答by avacariu

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

你可以逃避斜线。使用\\,你只会得到一个斜线。