[英]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.