本文共 2542 字,大约阅读时间需要 8 分钟。
python 原始字符串
Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
Python原始字符串是通过在字符串文字前加上'r'或'R'来创建的。 Python原始字符串将反斜杠(\)视为文字字符。 当我们想要一个包含反斜杠的字符串并且不希望将其视为转义字符时,这很有用。
Let’s say we want to create a string Hi\nHello in python. If we try to assign it to a normal string, the \n will be treated as a new line.
假设我们要在python中创建字符串Hi \ nHello 。 如果我们尝试将其分配给普通字符串,则\ n将被视为新行。
s = 'Hi\nHello'print(s)
Output:
输出:
HiHello
Let’s see how raw string helps us in treating backslash as a normal character.
让我们看看原始字符串如何帮助我们将反斜杠视为普通字符。
raw_s = r'Hi\nHello'print(raw_s)
Output: Hi\nHello
输出: Hi\nHello
Let’s see another example where the character followed by backslash doesn’t have any special meaning.
让我们看另一个示例,其中后面跟反斜杠的字符没有任何特殊含义。
>>> s = 'Hi\xHello' File "", line 1SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape
We got the error because python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning. Let’s see how we can create the same string using raw strings.
我们收到错误消息是因为python不知道如何解码'\ x',因为它没有任何特殊含义。 让我们看看如何使用原始字符串创建相同的字符串。
>>> s = r'Hi\xHello'>>> print(s)Hi\xHello
>>> r'Hi\xHello''Hi\\xHello'
Don’t get confused with the output having two backslashes. It’s just to show it as a normal where backslash is being escaped.
不要混淆具有两个反斜杠的输出。 只是将其显示为转义了反斜杠的普通 。
When a backslash is followed by a quote in a raw string, it’s escaped. However, the backslash also remains in the result. Because of this feature, we can’t create a raw string of single backslash. Also, a raw string can’t have an odd number of backslashes at the end.
当反斜杠后跟原始字符串中的引号时,将对其进行转义。 但是,反斜杠也保留在结果中。 由于此功能,我们无法创建单反斜杠的原始字符串。 另外,原始字符串的末尾不能有奇数个反斜杠。
Some of the invalid raw strings are:
一些无效的原始字符串是:
r'\' # missing end quote because the end quote is being escapedr'ab\\\' # first two backslashes will escape each other, the third one will try to escape the end quote.
Let’s look at some of the valid raw string examples with quotes.
我们来看一些带引号的有效原始字符串示例。
raw_s = r'\''print(raw_s)raw_s = r'ab\\'print(raw_s)raw_s = R'\\\"' # prefix can be 'R' or 'r'print(raw_s)
Output:
输出:
\'ab\\\\\"
That’s all for a quick introduction of python raw string.
这就是快速介绍python raw string的全部内容。
翻译自:
python 原始字符串
转载地址:http://damzd.baihongyu.com/