python原始字符串r
The prefix of 'u' in a string denotes the value of type Unicode rather than str. However, the Unicode strings are no longer used in Python3. The prefix of 'u' in a string denotes the value of type Unicode rather than str. However, the Unicode strings are no longer used in Python3.
字符串中的'u'前缀表示Unicode类型的值,而不是str。 但是,Python3中不再使用Unicode字符串。 字符串中的'u'前缀表示Unicode类型的值,而不是str。 但是,Python3中不再使用Unicode字符串。
In Python2, if we type a string literal without 'u' in front, we get the old str type which stores 8-bit characters, and with 'u' in front we get the newer Unicode type that can store any Unicode character.
在Python2中,如果键入的字符串文字前面没有'u' ,我们将得到存储8位字符的旧str类型,而前面带有'u'的我们将获得可以存储任何Unicode字符的较新的Unicode类型。
Additionally adding 'r' doesn't change the type of the literal, just changes how the string literal is interpreted. Without the 'r' backlashes (/) are treated as escape characters. With 'r' (/) are treated as literal.
另外,添加'r'不会改变文字的类型,只是改变字符串文字的解释方式。 没有'r'的反斜杠(/)被视为转义字符。 用'r' (/)视为文字。
原始字符串 (Raw strings)
Prefixing the string with 'r' makes the string literal a 'raw string'. Python raw string treats backslash (\) as a literal character, which makes it useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
给字符串加上'r'前缀会使字符串文字成为'raw string' 。 Python原始字符串将反斜杠( \ )视为文字字符,当我们希望包含反斜杠的字符串并且不希望将其视为转义字符时,它非常有用。
Consider the below example, where (\) has a special meaning.
考虑下面的示例,其中( \ )具有特殊含义。
s='Hi\nHello'
print(s)
r=r'Hi\nHello'
print(r)
Output
输出量
Hi
Hello
Hi\nHello
Consider the below example, where (\) doesn't have special meaning,
考虑下面的示例,其中(\)没有特殊含义,
s='Hi\xHello'
Output
输出量
File "main.py", line 1
s='Hi\xHello'
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape
s=r'Hi\xHello'
print(s)
Output
输出量
Hi\xHello
python原始字符串r