字符串"/>
7.字符串
7.1字符串编码转换
两种常用的字符串类型,分别是str和bytes。
str和bytes之间可以通过encode()和decode()方法进行转换,这两个方法是互为逆过程。
7.1.1使用encode()方法编码
encode()方法为str对象的方法,用于将字符串装换为二进制数据(即bytes),也称为“编码”,其语法格式如下:
str.encode([encoding=“utf-8”][,errors=“strict”])
str:表示要进行转换的字符串。
encoding=“utf-8”:可选参数,用于指定进行转码时采用的字符编码,默认为UTF-8。如果想使用简体中文,也可以设置为gb2312。当只有这一个参数时,也可以省略前面的“encoding=”,直接写编码。
errors=“strict”:可选参数,用于指定错误处理方式,其可选择值可以是strict(遇到非法字符就抛出异常)、ignore(忽略非法字符)、replace(用“?”替换非法字符)或xmlcharrefreplace(使用XML的字符引用)等,默认值为strict。
7.1.2使用decode()方法解码
decode()方法为bytes对象的方法,用于将二进制数据转换为字符串,即将使用encode()方法转换的结果再转换为字符串,也称为“解码”。
其语法格式如下:
bytes.decode([encoding=“utf-8”][,errors=“strict”])
string="我是一个中国人"
byte=string.encode(encoding="utf-8")
print(byte)
str=byte.decode(encoding="utf-8")
print(str)D:\python\python.exe E:/python/字符串/7.1字符串编码转换.py
b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\x80\xe4\xb8\xaa\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'
我是一个中国人
7.2字符串常用操作
7.2.1拼接字符串
使用“+”运算符可完成对多个字符串的拼接,字符串不允许直接与其他类型的数据拼接
str1 = “我爱中国”
str2=“我是中国人”
print(str1+"\n"+str2)
num = 21
try:
print(str1+num)
except:
print(“请拼接字符串类型的值”)
D:\python\python.exe E:/python/字符串/7.2.1拼接字符串.py
我爱中国
我是中国人
请拼接字符串类型的值
7.2.2计算字符串的长度
len(string)
str1='人生苦短,及时行乐'
print(len(str1))
byte1=str1.encode()
print(len(byte1))
byte2=str1.encode('gbk')
print(len(byte2))D:\python\python.exe E:/python/字符串/7.2.2计算字符串的长度.py
9
27
18
7.2.3截取字符串
string[start
更多推荐
7.字符串
发布评论