我想将一些mathjax代码保存到python中的.txt文件中。
x = "$\infty$"
with open("sampletext.txt", "a+") as f:
f.write(x)
完全按预期工作
sampletext.txt
$\infty$
但是,当我尝试将转义序列保存在列表中
x = ["$\infty$"]
with open("sampletext.txt", "a+") as f :
f.write(str(x))
sampletext.txt
['$\\infty$']
如何删除后者中的双反斜杠并将其另存为['$\infty$']
?
答案 0 :(得分:2)
也许这可以帮助您:
x = [r"$\infty$"]
with open("sampletext.txt", "a+") as f:
f.write(''.join(x))
标记“ r”(原始)可用于保存带有特殊符号(例如“ \”)的字符串
或者如果您不知道列表中有多少项:
x = ["$\infty$"]
with open("sampletext.txt", "a+") as f:
f.write(f"{''.join(x)}")
答案 1 :(得分:2)
尝试一下:
x = [r"$\infty$"]
with open("sampletext.txt", "a+") as f:
f.write(str(x))
r表示将字符串视为原始字符串,这意味着所有转义码都将被忽略。