python原始字符串r_“ u”和“ r”字符串标志的作用是什么?Python中的原始字符串文字是什么?...

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


翻译自: https://www.includehelp.com/python/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals.aspx

python原始字符串r

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值