I have a Python list:
instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
I want to write this list to a text file and escape the " characters. The final output I am looking for is:
[\"44433141537\", \"192797680391\", \"192773331481\", \"44433141641\", \"44434295873\"]
This string will ultimately end up being concatenated between two further [static] strings that I have manual escaped - the overall string is a graphQL query that is passed to a GraphQL API endpoint which needs quote marks and line feeds escaped.
I've tried:
escapedInstrumentList={json.dumps(instrumentList).replace("'","\'")}
but this outputs:
"[""44433141537"", ""192797680391"", ""192773331481"", ""44433141641"", ""44434295873""]"
Any guidance gratefully received.
Paul
Please try this:
instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
json.dumps(instrumentList).replace('"', '''\\"''')
If you want to convert your list of strings to a string that can be printed to a text file you can use this:
instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
output = '['+ ', '.join([f'\\"{item}\\"' for item in instrumentList]) + ']'
print(output)
Output as requirement.
import json, re
instrumentList=["44433141537", "192797680391", "192773331481", "44433141641", "44434295873"]
escapedInstrumentList= {re.sub('"', '/"', json.dumps(instrumentList)) }
print(escapedInstrumentList)
Try this one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.