python反斜杠的功能,Python转义反斜杠

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

解决方案

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

585e4769290a4e9e7afd8cd679001275.png

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.

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!

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值