编码
Python中默认 ASCII 格式,如果有中文使用utf-8编码。在文件开头加入 # -- coding: UTF-8 -- 或者 # coding=utf-8
注意:# coding=utf-8 的 = 号两边不要空格。
ASCII:英文、数字,1字节
utf-8:英文1字节,汉字3字节
Unicode:都是2字节
str转byte
1. bytes(s, encoding = "utf8")
2. s.encode('gbk')
byte转str
1. str(b, encoding = "utf-8")
2. b.decode('gbk')
字符串转换list,数值
1. list
join(list, '') list转str
split(str, '') str转list
2. 数值
str() 强转为字符串
int()/float() 强转为数值
字符串与文本序列化
import pickle
li = [1, 2, 3, 4]
#序列化list为str
s = pickle.dumps(li)
#反序列化str为list
l = pickle.loads(s)
print(s, l)
字符串与json
import json
jsonObject = {}
jsonObject[“a”] = 1
#json对象转str
jsonStr = json.dumps(jsonObject)
#str转json对象
jsonObject = json.loads(jsonStr)
#json对象写入文本
f = open("./my.json", ‘w’)
json.dump(jsonObject, f,)
f.close()
#读取文本内容并转为json对象
try:
f = open("./my.json", ‘r’)
jsonObject = json.load(f)
print(jsonObject)
print(type(jsonObject))
except Exception as e:
print(e)
finally:
f.close()
字符串查找替换
1. find() 查找,找不到返回-1
2. rfind() 反向查找,找不到返回-1
3. index() 同find,但是找不上产生异常
4. rindex() 同rfind,但是找不上发送异常
5. count() 查找子串个数
6. len() 字符串长度
7. startwith() 是否以某个子串开头
8. endwith() 是否以某个子串结尾
9. cmp() 比较
10. repleace() 替换
11. trim() 去除两边空格
12. re.sub(u'\u0000', "", s) 去除字符串结尾的\u0000