【问题标题】:How to format escape sequences inside a function [duplicate]如何在函数内格式化转义序列[重复]
【发布时间】:2024-01-04 11:23:01
【问题描述】:

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

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

vhf('n')

输出是:

...I want this \n escape sequence

但我希望它是:

...I want this
escape sequence

【问题讨论】:

标签: python python-2.7 function formatting escaping


【解决方案1】:

根据this线程,它讨论了一个类似的问题,你可以使用内置的String方法decode'string-escape'codec

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

【讨论】:

    【解决方案2】:

    由于您不使用字符串文字,因此请勿在 函数中使用转义序列。

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

    【讨论】: