简体   繁体   English

如何在字符串中使用 \\?

[英]How do I use \ in a string?

I am trying to create a directory in my Python code but I can't use backslash \\ in a string.我试图在我的 Python 代码中创建一个目录,但我不能在字符串中使用反斜杠\\ Every time I do it gives me an unexpected token error.每次我这样做都会给我一个意外的令牌错误。

I would like my code to look something like this:我希望我的代码看起来像这样:

dir = os.getcwd() + "\FolderIWantToCreate"

If I use / (forward slash), it gives me an error because my directory paths use backslash.如果我使用/ (正斜杠),它会给我一个错误,因为我的目录路径使用反斜杠。 However if I type \\ (backslash) anywhere in my code, even inside "" , it doesn't register the backslash as a string, it says unexpected token.但是,如果我在代码中的任何位置键入\\ (反斜杠),即使在"" ,它也不会将反斜杠注册为字符串,而是表示意外标记。

How can I overcome this?我怎样才能克服这个问题?

\\ is the escape character in python. \\ 是 python 中的转义字符。 If you want to use \\ in a string you have to escape it, ie:如果您想在字符串中使用 \\ ,则必须对其进行转义,即:

"\\"

For more, see: https://docs.python.org/2.0/ref/strings.html有关更多信息,请参阅: https : //docs.python.org/2.0/ref/strings.html

You have two options:您有两个选择:

  1. You can either escape the escape character \\ by adding an extra \\ before it, like this: "\\\\FolderIWantToCreate" ,您可以通过在转义字符\\之前添加一个额外的\\来转义它,如下所示: "\\\\FolderIWantToCreate"
  2. You can use the r prefix before the string to tell python that the string that follows is a raw string , like this: r"\\FolderIWantToCreate"您可以在字符串前使用r前缀来告诉 python 后面的字符串是原始字符串,如下所示: r"\\FolderIWantToCreate"

If you are dealing with paths and look eg for OS intercompatibility, consider using the pathlib package.如果您正在处理路径并寻找例如操作系统的pathlib ,请考虑使用pathlib包。 More info on how to use it when eg creating new folders, see here .有关如何在例如创建新文件夹时使用它的更多信息,请参见此处

If you really have to use that notation anyways, then an option would be to make it a "raw" string:如果您确实必须使用该符号,则可以选择将其设为“原始”字符串:

s = r'\FolderIWantToCreate'

more on that eg here .更多关于这方面的信息,例如这里

Please use the Escape sequence when ever you are using special characters使用特殊字符时请使用转义序列

dir = os.getcwd() + "\\FolderIWantToCreate"

Reference : 2.4.1 String literals参考: 2.4.1 字符串文字

dir = os.getcwd() + "\\\\FolderIWantToCreate"

Just adding another answer which I think you should know;只是添加另一个我认为您应该知道的答案;

Assuming you are on Windows假设您使用的是 Windows

You can use os.path.join() with os.sep to overcome the issue you are facing.您可以将os.path.join()os.sep一起使用来克服您面临的问题。

I do not have a Windows VM with me to give you a concrete example.我没有带 Windows 虚拟机给你一个具体的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM