7.字符串

编程入门 行业动态 更新时间:2024-10-09 20:25:01

7.<a href=https://www.elefans.com/category/jswz/34/1771434.html style=字符串"/>

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.字符串

本文发布于:2024-03-05 15:49:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1712721.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!