生成模板时避免使用换行符

时间:2017-04-03 15:19:58

标签: python string templates

我尝试使用Python标准库模块生成测试用例 string.Template

s = Template('''TestStep("0.1", "Signal match time: %d \n"
                "%s value: %d",
                SignalMatchTime,
                $QU_Signals,
                value); ''')

print(s.substitute(QU_Signals='Signal_1'))

问题是,在输出中" \ n" 字符替换为换行符。

TestStep("0.1", "Signal match time: %d
"
                "%s value: %d",
                SignalMatchTime,
                QU_AVL_STEA_DV,
                value);

必需的输出是:(我需要在输出文件中保存" \ n" 字符)

TestStep("0.1", "Signal match time: %d \n"
                "%s value: %d",
                SignalMatchTime,
                QU_AVL_STEA_DV,
                value);

有没有人知道如何避免它?

1 个答案:

答案 0 :(得分:2)

您可以将\n替换为\\n

我运行了以下代码:

from string import Template
file = open("testfile.txt", "w")

s = Template('''TestStep("0.1", "Signal match time: %d \n"
                "%s value: %d",
                SignalMatchTime,
                $QU_Signals,
                value); ''')

file.write(s.substitute(QU_Signals='Signal_1'))
file.write("\n\n\n\n") #To add some space between the writes

s = Template('''TestStep("0.1", "Signal match time: %d \\n"
                "%s value: %d",
                SignalMatchTime,
                $QU_Signals,
                value); ''')



file.write(s.substitute(QU_Signals='Signal_1'))

结果是:

`TestStep("0.1", "Signal match time: %d 
"
                "%s value: %d",
                SignalMatchTime,
                Signal_1,
                value); 



TestStep("0.1", "Signal match time: %d \n"
                "%s value: %d",
                SignalMatchTime,
                Signal_1,
                value); `