首页 > 文章列表 > 为什么Python中的原始字符串(r-strings)不能以反斜杠结尾?

为什么Python中的原始字符串(r-strings)不能以反斜杠结尾?

Python 原始字符串 反斜杠
222 2023-08-19

The r in r-strings means raw strings. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"n" consists of two characters −

  • a backslash and
  • 一个小写字母'n'。

String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r""" is a valid string literal consisting of two characters −

  • a backslash and
  • 一个双引号;

The r"" is not a valid string literal. Specifically, a raw string cannot end in a single backslash. A single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

For Windows pathnames, the Windows system calls accept forward slashes too −

f = open("/mydir/demo.txt")

Pathname for a DOS command −

dir = r"thisismydosdir" ""
dir = r"thisismydosdir "[:-1]
dir = "thisismydosdir"