python用双反斜杠替换单反斜杠 [英] python replace single backslash with double backslash
问题描述
在python中,我试图用双反斜线(\")替换单反斜线(\").我有以下代码:
directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
然而,这会给出一条错误消息,指出它不喜欢双反斜杠.有人可以帮忙吗?
此处无需使用 str.replace
或 string.replace
,只需将该字符串转换为原始字符串:
下面是上述字符串的 repr
版本,这就是您在此处看到 \\
的原因.但是,实际上实际的字符串只包含 '\'
而不是 \\
.
但是当你要打印这个字符串时,你不会在输出中得到 '\\'
.
如果您希望字符串在 print
期间显示 '\\'
然后使用 str.replace
:
repr
版本现在将显示 \\\\
:
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屋!