簡體   English   中英

如何以編程方式將反斜杠引號轉換為雙反斜杠引號?

[英]How to programmatically convert a backslash quote to a double backslash quote?

例如,如何以編程方式將 Python 3 字符串變量中的 \" 轉換為 \\"。

str1 = """

"this is a string \"and this is whatever\" and then some"

"""

這些是我不起作用的嘗試:

str2 = re.sub('\\"', '\\\\', str1)
print('Attempt #1) ' + str2)

and

str3 = str1.replace('\"', '\\"')
print ('Attempt #2) ' + str3)

這兩種嘗試都沒有產生我想要做的事情,我試圖以編程方式 output 的 output 是:

“這是一個字符串 \\”,這是什么 \\”,然后是一些”

你需要這樣做

str1 = r"""

"this is a string \"and this is whatever\" and then some"

"""

print('\\\\'.join(str1.split("\\")))

使用 'r' 將字符串轉換為原始字符串,這樣可以防止轉義序列解釋。

代碼是這樣的:

print("this is a string \\\\\" and this is whatever\\\\\" and then some")

你需要兩個反斜杠為每個\和另一個反斜杠來獲得"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM