【问题标题】:Python putting r before unicode string variablePython将r放在unicode字符串变量之前
【发布时间】:2015-06-06 00:56:09
【问题描述】:

对于静态字符串,将r 放在字符串前面将给出原始字符串(例如r'some \' string')。由于不可能将 r 放在 unicode 字符串变量前面,将字符串变量动态转换为其原始形式的最小方法是什么?我应该手动将所有反斜杠替换为双反斜杠吗?

str_var = u"some text with escapes e.g. \( \' \)"
raw_str_var = ???

【问题讨论】:

    标签: python string python-2.7 encoding


    【解决方案1】:

    如果您确实需要转义字符串,假设您想将换行符打印为\n,您可以使用encode 方法和Python 特定的string_escape 编码:

    >>> s = "hello\nworld"
    >>> e = s.encode("string_escape")
    >>> e
    "hello\\nworld"
    >>> print s
    hello
    world
    >>> print e
    hello\nworld
    

    您没有提及任何有关 unicode 或您使用的 Python 版本的信息,但如果您正在处理 unicode 字符串,您应该改用 unicode_escape

    >>> u = u"föö\nbär"
    >>> print u
    föö
    bär
    >>> print u.encode('unicode_escape')
    f\xf6\xf6\nb\xe4r
    

    您的帖子最初带有正则表达式标签,也许re.escape 是您真正想要的?

    >>> re.escape(u"foo\nbar\'baz")
    u"foo\\\nbar\\'baz"
    

    不是“双重转义”,即打印上面的字符串产生:

    foo\
    bar\'baz
    

    【讨论】:

    • encode('unicode_escape') 只转义 unicode 字符并忽略反斜杠: >>> s = u"fooo \' bar " >>> s.encode('unicode_escape') "fooo ' bar "
    • 不,这是因为 ' 字符一开始就不需要转义。在我的示例中,换行符被正确转义。
    • u"fooo \' bar " → u"fooo ' bar "
    • unicode_escape 的行为似乎与string_escape 不同:'>>> 'fooo \' bar'.encode('string_escape') -> "fooo \\' bar" ; >>> u'fooo \' bar'.encode('unicode_escape') -> "fooo ' bar"
    • 是的,那里似乎有细微的差别。请参阅this answer。如果您想完全控制转义机制,您可能必须自己实现它。你的用例是什么?
    【解决方案2】:

    没有什么可转换的 - r 前缀仅在源代码表示法中有意义,对程序逻辑没有意义。

    通常,如果您在普通字符串中使用单个反斜杠,如果它没有开始有效的转义序列,它将自动转换为双反斜杠:

    >>> "\n \("
    '\n \\('
    

    由于可能难以记住所有有效/无效的转义序列,因此引入了原始字符串表示法。但是没有办法,也不需要在定义字符串后进行转换。

    在您的情况下,正确的方法是使用

    str_var = ur"some text with escapes e.g. \( \' \)"
    

    这恰好在此处产生相同的字符串,但更明确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-30
      • 2023-04-06
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2019-10-17
      • 2012-05-05
      • 2020-05-31
      相关资源
      最近更新 更多