[英]python replace single backslash with double backslash
在python中,我试图用双反斜杠(“\\”)替换单个反斜杠(“\\”)。 我有以下代码:
directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
但是,这会给出一条错误消息,指出它不喜欢双反斜杠。 任何人都可以帮忙吗?
这里不需要使用str.replace
或string.replace
,只需将该字符串转换为原始字符串:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
以下是上述字符串的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
但是当你要打印这个字符串时,你不会在输出中得到'\\\\'
。
>>> print strs
C:\Users\Josh\Desktop\20130216
如果您希望字符串在print
期间显示'\\\\'
然后使用str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr
版本现在将显示\\\\\\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
让我说得简单明了。 让我们使用 python 中的 re 模块来转义特殊字符。
Python脚本:
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
输出 :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
解释 :
function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.现在观察转义给定字符串中特殊字符的函数,我们能够在每个反斜杠之前添加另一个反斜杠,最后输出结果为双反斜杠,即所需的输出。
希望这对你有帮助。
使用转义字符: "full\\\\path\\\\here"
、 "\\\\"
和"\\\\\\\\"
在python中\\
(反斜杠)用作转义字符。 这意味着在您希望插入特殊字符(例如换行符)的地方,您将使用反斜杠和另一个字符( \\n
表示换行符)
使用您的示例字符串,您会注意到,当您将"C:\\Users\\Josh\\Desktop\\20130216"
放入 repl 时,您将获得"C:\\\\Users\\\\Josh\\\\Desktop\\x8130216"
。 这是因为\\2
在 python 字符串中具有特殊含义。 如果您希望指定\\
则需要在字符串中放置两个\\\\
。
"C:\\\\Users\\\\Josh\\\\Desktop\\\\28130216"
另一种选择是通过在字符串前面加上r
来通知 python 您的整个字符串不得使用\\
作为转义字符
r"C:\\Users\\Josh\\Desktop\\20130216"
这是一个“原始”字符串,在需要使用大量反斜杠(例如正则表达式字符串)的情况下非常有用。
如果您仍然希望用\\\\
替换单个\\
,则可以使用:
directory = string.replace(r"C:\\Users\\Josh\\Desktop\\20130216", "\\\\", "\\\\\\\\")
请注意,我没有在上面的最后两个字符串中使用r'
。 这是因为,当您使用r'
形式的字符串时,您不能以单个\\
结尾该字符串
您的情况可能存在语法错误,您可以将该行更改为:
directory = str(r"C:\Users\Josh\Desktop\20130216").replace('\\','\\\\')
这为您提供了正确的以下输出:
C:\\Users\\Josh\\Desktop\\20130216
反斜杠表示特殊的转义字符。 因此, directory = path_to_directory.replace("\\", "\\\\")
会导致 Python 认为要替换的第一个参数直到第二个参数的起始引号才结束,因为它将结束引号理解为转义字符.
directory=path_to_directory.replace("\\","\\\\")
你可以用
os.path.abspath(path_with_backlash)
它返回带有\\
的路径
用:
string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")
转义\\
字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.