【问题标题】:Programatically adding escape characters to Python List以编程方式将转义字符添加到 Python 列表
【发布时间】:2020-08-27 10:21:50
【问题描述】:

我有一个 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""]"

感谢您的任何指导。

保罗

【问题讨论】:

  • [\"44433141537\", \"192797680391\", \"192773331481\", \"44433141641\", \"44434295873\"] - 你确定这件事吗?显示更多上下文,因为就其本身而言,这种特殊格式似乎没有多大意义。
  • 试试repr(instrumentList).replace("'", r"\'"))
  • fr'\"{"44433141537"}\"' - `

标签: python graphql escaping


【解决方案1】:

请试试这个:


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

【讨论】:

    【解决方案2】:
    import json, re
    instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
    escapedInstrumentList= {re.sub('"', '/"', json.dumps(instrumentList)) }
    print(escapedInstrumentList)
    

    试试这个。

    【讨论】:

      【解决方案3】:

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

      instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
      
      output = '['+ ', '.join([f'\\"{item}\\"' for item in instrumentList]) + ']'
      
      print(output)
      

      按要求输出。

      【讨论】:

      • 这种方法给了我想要达到的最佳结果,谢谢。
      猜你喜欢
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多