【问题标题】:Cleaning escapes on a user-entered string [duplicate]清理用户输入的字符串上的转义符[重复]
【发布时间】:2021-03-28 07:05:58
【问题描述】:

我有一个用户可以输入程序在解析后打印的文本。也就是说,用户可以输入如下内容:

"Print me\nAnd on a newline now"

它应该打印为:

Print me
And on a newline now

当我打印它时,我现在拥有的字符串看起来像OK\n,当我在它上面执行repr() 时,它看起来像OK\\n。我在将其转换为正确打印换行符时遇到了一些困难。现在唯一可行的方法是手动检查每个可能的条目并执行以下操作:

val = val.replace('\\n', '\n'))
# or, what if they wanted a beep?
# similar to print('\a')

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以使用astshlex 来完成工作。

    >>import ast
    >>import shlex
    >>x = input('Enter the string:')
    Enter the string:>? "Print me\nAnd on a newline now"
    >>x
    '"Print me\\nAnd on a newline now"'
    

    输出

    print(ast.literal_eval(shlex.quote(x)))
    "Print me
    And on a newline now"
    

    更新:正如@David542 所指出的,如果您不想使用shlex,甚至可以避免使用

    >>print(ast.literal_eval("'%s'" % x))
    "Print me
     And on a newline now"
    

    【讨论】:

    • 酷。如果没有 shlex 而只是做:print(ast.literal_eval("'%s'" % x)) 呢?
    • @David542,那就更酷了。
    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 2013-09-22
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多