简体   繁体   English

Python转义反斜杠

[英]Python escaping backslash

I'm trying to escape the backslash, but trying to understand the right way of doing it我试图逃避反斜杠,但试图理解正确的做法

foo = r'C:\Users\test.doc'

The above works fine以上工作正常

However, when I want to escape the path stored in a variable但是,当我想转义存储在变量中的路径时

For example :例如 :

parser.add_argument('-s', '--source', type = str, help = 'Source file path')

Now, how do escape the value in - args.source现在,如何转义 - args.source 中的值

So there are a few escape sequences to be aware of in python and they are mainly these.所以在python中有一些转义序列需要注意,它们主要是这些。

在此处输入图像描述

So when the string for that file location is parsed by the add_argument method it may not be interpreted as a raw string like you've declared and there will be no way to escape the backslashes outside of the declaration.因此,当add_argument方法解析该文件位置的字符串时,它可能不会像您声明的那样被解释为原始字符串,并且无法在声明之外转义反斜杠。

What you can do instead is to keep it as a regular string (removing the 'r' prefix from the string) and using the escape character for a backslash in any places there may be conflict with another escape character (in this case \\t).您可以做的是将其保留为常规字符串(从字符串中删除 'r' 前缀)并在任何可能与另一个转义字符冲突的地方使用转义字符作为反斜杠(在这种情况下为 \\t) . This may work as the method may evaluate the string correctly.这可能会起作用,因为该方法可以正确评估字符串。

Try declaring your string like this.尝试像这样声明你的字符串。

foo = "C:\Users\\test.doc"

Hopefully this helps fix your issue!希望这有助于解决您的问题!

EDIT:编辑:

In response to handling the dynamic file location you could maybe do something like the following!为了响应处理动态文件位置,您可能会执行以下操作!

def clean(s):
    s = s.replace("\t", "\\t")
    s = s.replace("\n", "\\n")
    return s

Until you've covered all of your bases with what locations you may need to work with!直到您覆盖了所有基地以及您可能需要使用的位置! This solution might be more appropriate for your needs.此解决方案可能更适合您的需求。 It's kind of funny I didn't think of doing it this way before.有点滑稽,我以前没想过这样做。 Hopefully this helps!希望这会有所帮助!

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

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