Python转义反斜杠 [英] Python escaping backslash

查看:146
本文介绍了Python转义反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图逃避反斜杠,但试图理解正确的方法

I'm trying to escape the backslash, but trying to understand the right way of doing it

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

上面的方法很好

但是,当我想转义存储在变量中的路径

However, when I want to escape the path stored in a variable

例如:

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

现在,如何在-args.source

Now, how do escape the value in - args.source

推荐答案

因此在python中需要注意一些转义序列,主要是这些。

So there are a few escape sequences to be aware of in python and they are mainly these.

因此,当该文件位置的字符串由<$解析时c $ c> add_argument 方法,它可能不会像您声明的那样被解释为原始字符串,并且将无法在声明之外转义反斜杠。

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.

W您可以做的是将其保留为常规字符串(从字符串中删除 r前缀),并在任何可能与另一个转义字符冲突的地方使用转义字符进行反斜杠(在这种情况下为\t )。

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). 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!

编辑:

在对于处理动态文件位置的响应,您可以执行以下操作!

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!

这篇关于Python转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆