浅析Python字符串中的r和u的区别

2022-07-20,,,

目录
  • 1.r(r)
  • 2.u(u)
  • 补充
  • 参考文献

python字符串前面我们经常看到加r(r)或u/(u)的前缀,而这两个符号是什么意思呢?

1.r(r)

r意为raw,表示不包含转义字符的原生字符串。常见的转义字符包括下列几种:

转义字符 描述
\(在行尾时) 续航符
\\ 反斜杠符号
' 单引号(字符串需要为""形式)
" 双引号(需要字符串用需要为''形式)
\b 退格(backspace)
\000
\n 换行
\v 纵向制表符
\t 横向制表符

下面是几个转义字符的演示:

print("hello\
,world")
# hello,world
print("hello\\,world")
# hello\,world
print("hello',world")
# hello',world
print('hello",world')
# hello",world
print("hello\b,world")
# hell,world
print("hello\000,world")
#hello,world
print("hello\n,world")
# hello
# ,world
print("hello\v,world")
# hello
#      ,world
print("hello\t,world")
# hello   ,world
print("hello\020,world")

r前缀的作用就是告诉解释器,我这个字符串不包含转义字符,比如字符串中如果包含'\n',则不将其视为换行符,而视为一个'\'字符和'n'字符来处理。如下面所示:

print("hello,\nworld")
# hello,
# world
print("hello,\nworld")
# hello,\nworld

r前缀最常见的用途是正则表达式,因为正则匹配的模式经常包含各种反斜杠等字符,我们不希望它被解析为转移字符,因此需要加上'r'。

import re
str_pat= re.compile(r'\d+/\d+/\d+')
text = 'today is 12/10/2021, yesterday is 12/11/2021'
res = str_pat.findall(text)
print(res)
['12/10/2021', '12/11/2021']

2.u(u)

u(u)前缀表示字符串的编码方式为unicode。不仅包含中文在内的任意字符串都可以采用unicode编码。一般英文字符串在任何编码的情况下都能正常解析,所以一般不用显式添加u。然而中文最好要说明其编码,否则编码转换时就会出现乱码(比如本来用gbk编码但拿unicode来解码)。解决编码问题一劳永逸的方法是在.py的文件头添加如下内容:

# coding: utf-8

补充

字符串前加b

例: response = b'<h1>hello world!</h1>'     # b' ' 表示这是一个 bytes 对象

作用:

b" "前缀表示:后面字符串是bytes 类型。

用处:

网络编程中,服务器和浏览器只认bytes 类型数据。

如:send 函数的参数和 recv 函数的返回值都是 bytes 类型

附:

在 python3 中,bytes 和 str 的互相转换方式是

str.encode('utf-8')
bytes.decode('utf-8')

字符串前加f

import time
t0 = time.time()
time.sleep(1)
name = 'processing'
# 以 f开头表示在字符串内支持大括号内的python 表达式
print(f'{name} done in {time.time() - t0:.2f} s')

输出:

processing done in 1.00 s

参考文献

[1] https://www.python.org/

[2] martelli a, ravenscroft a, ascher d. python cookbook[m]. " o'reilly media, inc.", 2005.

到此这篇关于浅析python字符串中的r和u的区别的文章就介绍到这了,更多相关python字符串内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《浅析Python字符串中的r和u的区别.doc》

下载本文的Word格式文档,以方便收藏与打印。