在Python中如何在字符串中插入反斜杠?

2024-04-26 04:09:41 发布

您现在位置: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


Tags: 文件the实例字符串jsonstringarereplace
2条回答

忽略这样一个事实,即您应该使用json方法来完成您试图实现的任务:Replace返回一个带有修改后的子字符串的新字符串。因此,您的方法是正确的,您只需重新分配:

string = "\"The strings themselves are quotes, formatted like this\" - Some Guy"
string = string.replace("\"", "\\\"")

print(string)

这将为您提供:

\"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))

相关问题 更多 >