Python 原始文字字符串 [英] Python raw literal string

查看:45
本文介绍了Python 原始文字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

str = r'c:\path\to\folder\'   # my comment

  • IDE:Eclipse
  • Python2.6
  • 当字符串中的最后一个字符是反斜杠时,它似乎会转义最后一个单引号并将我的评论视为字符串的一部分.但是原始字符串应该忽略所有转义字符,对吗?可能有什么问题?谢谢.

    When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? What could be wrong? Thanks.

    推荐答案

    原始字符串文字不会将反斜杠视为启动转义序列 除非 当紧随其后的字符是引号字符时分隔文字,在这种情况下,反斜杠确实将其转义.

    Raw string literals don't treat backslashes as initiating escape sequences except when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash does escape it.

    设计动机是原始字符串字面量的真正存在只是为了方便输入正则表达式模式–就是这样,对于此类文字,没有 存在其他设计目标.RE 模式永远不需要以反斜杠结尾,但它们可能需要包含各种引号字符,这就是规则.

    The design motivation is that raw string literals really exist only for the convenience of entering regular expression patterns – that is all, no other design objective exists for such literals. And RE patterns never need to end with a backslash, but they might need to include all kinds of quote characters, whence the rule.

    许多人确实尝试使用原始字符串文字来使他们能够以他们习惯的方式(使用反斜杠)输入 Windows 路径 –但是正如您已经注意到的那样,当您确实需要一条以反斜杠结尾的路径时,这种用法就会失效.通常,最简单的解决方案是使用 forward 斜杠,Microsoft 的 C 运行时和所有版本的 Python 都支持在路径中完全等效:

    Many people do try to use raw string literals to enable them to enter Windows paths the way they're used to (with backslashes) – but as you've noticed this use breaks down when you do need a path to end with a backslash. Usually, the simplest solution is to use forward slashes, which Microsoft's C runtime and all version of Python support as totally equivalent in paths:

    s = 'c:/path/to/folder/'
    

    (旁注:不要用你自己的标识符遮蔽内置名称,比如 str ——这是一种可怕的做法,没有任何好处,除非你得到养成避免这种可怕做法的习惯,有一天你会发现自己遇到了令人讨厌的调试问题,当你的代码的某些部分践踏了内置名称而另一部分需要使用内置真正意义上的名字).

    (side note: don't shadow builtin names, like str, with your own identifiers – it's a horrible practice, without any upside, and unless you get into the habit of avoiding that horrible practice one day you'll find yourseld with a nasty-to-debug problem, when some part of your code tramples over a builtin name and another part needs to use the builtin name in its real meaning).

    这篇关于Python 原始文字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆