[英]How to insert a backslash into a string in Python?
我正在編寫一個Python程序,該程序創建一個JSON文件作為其輸出。 在JSON文件中有字符串,並且在這些字符串中有引號。 我想使用反斜杠轉義那些引號,而這樣做的唯一方法是將反斜杠插入到我正在寫入此文件的字符串中。 我如何在字符串中插入反斜杠而不將其用作轉義符?
我正在嘗試使用.replace
字符串函數將所有實例"
替換為\\"
。 我也嘗試過用"
\\\\"
和\\\\\\"
實例替換"
所有實例,但是這些都不起作用。
string = "\"The strings themselves are quotes, formatted like this\" - Some Guy"
string.replace("\"","\\\"") # Just doing \\" gives me an error as the backslashes cancel each other out, leaving you just three quote marks.
我正在嘗試獲取字符串以輸出確切的短語: \\"The strings themselves are quotes, formatted like this\\" - Some Guy
如之前的評論所建議,您可能正在尋找:
import json
string = "\"The strings themselves are quotes, formatted like this\" - Some Guy"
print(json.dumps(string))
忽略這一事實,您應該使用json方法來完成您要實現的目標:Replace返回帶有修改后的子字符串的新字符串。 因此,您的方法是正確的,只需要重新分配即可:
string = "\"The strings themselves are quotes, formatted like this\" - Some Guy"
string = string.replace("\"", "\\\"")
print(string)
這給您:
\\“字符串本身是引號,格式如下\\”-Some Guy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.