如何在函数中格式化转义序列

2024-09-26 22:53:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在函数中导入一个值,该值将作为函数应该打印的字符串的转义序列。非常感谢您的帮助

def vhf(c):
    print "...I want this \%s escape sequence" % c

vhf('n')

输出为:

...I want this \n escape sequence

但我希望是:

...I want this
escape sequence

Tags: 函数字符串defthisprintsequencewantescape
2条回答

根据讨论了类似问题的this线程,您可以将内置的字符串方法decode'String-escape'codec一起使用:

def vhf(c):
    s = "...I want this \\" + c + " escape sequence"
    print s.decode('string_escape')

因为您不使用字符串文字,所以不要在函数中使用转义序列

def vhf(c):
    print "...I want this %s escape sequence" % (c,)

vhf('\n')

相关问题 更多 >

    热门问题