Jos*_*ood 38 python string replace backslash
在python中,我试图用双反斜杠("\")替换单个反斜杠("\").我有以下代码:
directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
Run Code Online (Sandbox Code Playgroud)
但是,这会给出一条错误消息,说它不喜欢双反斜杠.有人可以帮忙吗?
Ash*_*ary 48
无需使用str.replace
或string.replace
在此处,只需将该字符串转换为原始字符串:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Run Code Online (Sandbox Code Playgroud)
下面是repr
上面字符串的版本,这就是你在\\
这里看到的原因.但是,事实上实际的字符串只包含'\'
没有\\
.
>>> 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
Run Code Online (Sandbox Code Playgroud)
但是当你要打印这个字符串时,你不会进入'\\'
输出.
>>> print strs
C:\Users\Josh\Desktop\20130216
Run Code Online (Sandbox Code Playgroud)
如果您希望'\\'
在print
使用期间显示字符串str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
Run Code Online (Sandbox Code Playgroud)
repr
版本现在将显示\\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Run Code Online (Sandbox Code Playgroud)
Rew*_*ool 12
让我简单明了.让我们使用python中的re模块来转义特殊字符.
Python脚本:
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Run Code Online (Sandbox Code Playgroud)
输出:
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Run Code Online (Sandbox Code Playgroud)
说明:
现在观察re.escape函数在转义给定字符串中的特殊字符时我们能够在每个反斜杠之前添加另一个反斜杠,最后输出结果是双反斜杠,即所需的输出.
希望这对你有所帮助.
归档时间: |
|
查看次数: |
69331 次 |
最近记录: |