python用双反斜杠替换单反斜杠 [英] python replace single backslash with double backslash

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

问题描述

在python中,我试图用双反斜线(\")替换单反斜线(\").我有以下代码:

directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")

然而,这会给出一条错误消息,指出它不喜欢双反斜杠.有人可以帮忙吗?

解决方案

此处无需使用 str.replacestring.replace ,只需将该字符串转换为原始字符串:

<预><代码>>>>strs = r"C:\Users\Josh\Desktop\20130216"^|注意'r'

下面是上述字符串的 repr 版本,这就是您在此处看到 \\ 的原因.但是,实际上实际的字符串只包含 '\' 而不是 \\.

<预><代码>>>>字符串'C:\\用户\\Josh\\桌面\\20130216'>>>s = r"f\o">>>s #repr 表示'f\\o'>>>len(s) #length 是 3,因为只有一个 `'\'`3

但是当你要打印这个字符串时,你不会在输出中得到 '\\' .

<预><代码>>>>打印字符串C:\用户\乔希\桌面\20130216

如果您希望字符串在 print 期间显示 '\\' 然后使用 str.replace:

<预><代码>>>>new_strs = strs.replace('\\','\\\\')>>>打印 new_strsC:\\用户\\Josh\\桌面\\20130216

repr 版本现在将显示 \\\\:

<预><代码>>>>新字符串'C:\\\\用户\\\\Josh\\\\桌面\\\\20130216'

In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:

directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")

However, this gives an error message saying it doesn't like the double backslash. Can anyone help?

解决方案

No need to use str.replace or string.replace here, just convert that string to a raw string:

>>> strs = r"C:\Users\Josh\Desktop\20130216"
           ^
           |
       notice the 'r'

Below is the repr version of the above string, that's why you're seeing \\ here. But, in fact the actual string contains just '\' not \\.

>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'

>>> s = r"f\o"
>>> s            #repr representation
'f\\o'
>>> len(s)   #length is 3, as there's only one `'\'`
3

But when you're going to print this string you'll not get '\\' in the output.

>>> print strs
C:\Users\Josh\Desktop\20130216

If you want the string to show '\\' during print then use str.replace:

>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216

repr version will now show \\\\:

>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'

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

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