1 python中字符串的定义
可以使用英文的单引号、双引号定义或三个引号(英文的单引号或双引号)字符串
x='abc'
y="abc"
注意:
字符串中出现的特殊字符需要使用转义字符处理\
x='abc\'d' #经过转义字符处理后变成字符串常量
print(x)
结果
abc'd
最无厘头的字符串合并
str="hello""world"
print(str)
2 str和repr函数
str函数,如果出现转义字符,转换成对应的显示功能,例如,\n变成换行;
repr函数,如果字符串中出现转义字符则保持原貌,不进行转换处理
注意:
在原始字符串前加r效果等同于repr函数
如:
s=r"hello\nworld"
print(s)
注意:
str()函数作用,将数据强制转换成字符串类型
例 将数值转换成字符串
x=70
y=x*3
#将x转成了字符串
mstr=str(x)
#序列乘法
mstr=mstr*3
print(y,mstr)
结果
210 707070
例 将元组通过str()函数转换成字符串
mlist=(7,8)
mstr=str(mlist)
mlist=mlist*2
mstr=mstr*2
print(mlist,mstr,sep='\n')
结果
(7,8,7,8)
(7,8)(7,8)
3 字符串的编码
例 字符串得到对应编码
s1='中文'.encode("utf-8")
print(s1)
s2='hello'.encode('utf-32')
print(s2)
s3='hello'.encode('ascii')
print(s3)
结果
b'\xe4\xb8\xad\xe6\x96\x87'
b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00'
b'hello'
例 得到字节数组的bytes函数
by=bytes("hello",encoding="utf-8")
例 通过字节数组常量得到对应的字符串
s=str(b'H\xc3\xa6ll\xc3\xa5', encoding="utf-8")
print(s)
注意:
b'....' 字节形式的字符串
str函数按utf-8重新编码为字符串
#字符串常量不能修改
s=b"abc"
s[2]='d'
print(s)
针对字符串不能修改,可以使用bytearray函数先转换成字节数组
按索引位置修改必须使用ord函数
by=bytearray(s)
by[1]=ord(b'n')
print(by)