编码问题
2中打印str显示前面加了个u且中文类似\u8be5\u9879:这是十六进制的Unicode编码,使用
string.encode('utf-8')
进行转换2中类似\uiahd\u9483这样的字符串:需要注意的是,该字符串本来就是这样,而不是编码成这样的,这时候需要反编码:
string.decode('unicode_escape'))
无法解析\u2c这样的unicode字符,出现错误
UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-3:truncated \uXXXX escape
: 原因是unicode默认是\uxxxx这样的形式来解析字符串的,但是如果出现\u2c
这种,是解析不了的,应该写成\u002c
这种形式,前面需要补全url编码 Python3中,url编码放在了url lib.parse中了
123from urllib import parseparse.quote(str)parse.quote_plus(str)bytes to string
1b"abcde".decode('utf-8')将字符串输出为16进制字节:
1234":".join("\{:02x\}".format(ord(x) for x in 字符串))# 或":".join("\{0:x\}".format(ord(x) for x in 字符串))# 输出类似于: 12:45:4516进制转换为utf-8 :类似
\xe5\x94\xae\
这种,使用如下方式进行转换1unicode(string, 'utf-8')查看字符编码
12import chardetchardet.detect(string)
常用操作
|
|
查找与替换
|
|
时间处理
|
|
TroubleShooting
“TypeError: Unicode-objects must be encoded before hashing”
原因是在3.x中,md5方法仅接受unicode编码过后的字符串:
1hashlib.md5(string.encode('utf-8')).hexdigest()