以编程方式将转义字符添加到 Python 列表

Programatically adding escape characters to Python List

我有一个 Python 列表:

instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]

我想将此列表写入文本文件并转义 " 字符。我要查找的最终输出是:

[\"44433141537\", \"192797680391\", \"192773331481\", \"44433141641\", \"44434295873\"]

这个字符串最终将连接在我手动转义的另外两个 [静态] 字符串之间 - 整个字符串是一个 graphQL 查询,它被传递到需要引号的 GraphQL API 端点和换行符已转义。

我试过:

escapedInstrumentList={json.dumps(instrumentList).replace("'","\'")}

但这输出:

"[""44433141537"", ""192797680391"", ""192773331481"", ""44433141641"", ""44434295873""]"

非常感谢收到任何指导。

保罗

如果您想将字符串列表转换为可打印到文本文件的字符串,您可以使用此方法:

instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]

output = '['+ ', '.join([f'\"{item}\"' for item in instrumentList]) + ']'

print(output)

按要求输出。

import json, re
instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
escapedInstrumentList= {re.sub('"', '/"', json.dumps(instrumentList)) }
print(escapedInstrumentList)

试试这个。

请试试这个:


instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
json.dumps(instrumentList).replace('"', '''\"''')