简体   繁体   中英

How to save escape sequences to a file in python without double backslashes?

I want to save some mathjax code to a.txt file in python.

x = "$\infty$"
with open("sampletext.txt", "a+") as f:
    f.write(x)

Works exactly as expected

sampletext.txt

$\infty$

However when i try to save the escape sequence in a list

x = ["$\infty$"]
with open("sampletext.txt", "a+") as f  :
    f.write(str(x))

sampletext.txt

['$\\infty$']

How do i remove the double backslash in the latter and save it as ['$\infty$'] ?

Maybe this can help you:

x = [r"$\infty$"]
with open("sampletext.txt", "a+") as f:
    f.write(''.join(x))

Flag "r" (raw) can be use to save string with special symbols like "\"

Or if you don't know how many items in the list:

x = ["$\infty$"]
with open("sampletext.txt", "a+") as f:
    f.write(f"{''.join(x)}")

Try this:

x = [r"$\infty$"]
with open("sampletext.txt", "a+") as f:
    f.write(str(x))

The r means that the string is to be treated as a raw string, which means all escape codes will be ignored.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM