[英](Python) Print all '\' escape characters
我有幾個帶有\\
字符串。 我嘗試通過使用這樣的替換函數來不使用轉義字符:
string.replace("\\", "\\\\")
這是行不通的。
當我直接將string.replace("\\n", "\\\\n")
用於\\n
,它可以工作。 有沒有一個簡單的工作解決方案?
重要的是要注意,replace 不會作用於變量,而是返回應用了替換的副本,請參閱 文檔:
this = "string\\string"
this.replace("\\", "")
print(this)
>"string\\string"
如果你想替換原來的字符串,
this = this.replace("\\", "")
但是,要轉換\\n -> n
需要您對此有不同的看法。 即replace('\\n', 'n')
,因為\\n
是單個字符。
你可以試試這個:
def test():
foo = r"this is a \\ and this is a \ "
foo = foo.replace("\\" , r'\\') # added the r to ignore string escapes as escapes
print(foo)
test()
輸出:
this is a \\\\ and this is a \\
使用原始字符串。
r"This \ string \ includes '\'s"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.