字符串前加 r
r"" 的作用是去除转义字符.
即如果是“\n”那么表示一个反斜杠字符,一个字母n,而不是表示换行了。
以r开头的字符,常用于正则表达式,对应着re模块。
str1= 'input\n'
str= r'input\n'
print(str1)
print(str)
输出:
input
input\n
字符串前加 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')
u/U:表示unicode字符串
不是仅仅是针对中文, 可以针对任何的字符串,代表是对字符串进行unicode编码。
一般英文字符在使用各种编码下, 基本都可以正常解析, 所以一般不带u;但是中文, 必须表明所需编码, 否则一旦编码转换就会出现乱码。
建议所有编码方式采用utf8
u'input\n' # unicode编码字符,python3默认字符串编码方式。
字符串前加 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