Python知识笔记(+3):在定义字符串前面加b、u、r、f的含义

1. python中定义字符串前面加b、u、r的含义

1.1 基本格式

str = b"xxxx"
str = u"xxxx"
str = r"xxxx"
str = f"xxxx"

1.2 描述及对比

(1)字符串前面加b表示后面字符串是bytes类型,以便服务器或浏览器识别bytes数据类型;
(2)字符串前面加u表示以Unicode格式进行编码,往往用来解决中文乱码问题,一般英文字符串基本都可以正常解析,而中文字符串必须表明用什么编码,否则就会乱码。
(3)字符串前面加r表示以raw string格式进行定义,可以防止字符串规避反斜杠\的转义。
例如:

str1 = "\thello"
str2 = r"\thello"
print("str1 =",str1)
print("str2 =",str2)

输出

str1 =  	hello
str2 = \thello

(4)字符串前面加f表示能支持大括号里面的表达式。
例如:

python = "蟒蛇"

print("我要好好学{python}!")

print(f"我要好好学{
      
      python} !")

输出

我要好好学{
    
    python} !
我要好好学蟒蛇 !

(5)在python3中,bytesstr的相互转换

str.encode('utf-8')

bytes.decode('utf-8')

例如:

print("你好".encode(encoding="utf-8"))

输出b'\xe4\xbd\xa0\xe5\xa5\xbd'

print(b'\xe4\xbd\xa0\xe5\xa5\xbd'.decode())

输出你好

往往用于图片、音视频等文件的读写时,可用bytes数据。

猜你喜欢

转载自blog.csdn.net/A33280000f/article/details/121075746