python解码编码decode encoode

目录

1.decode解码

2.encode编码

3.特殊符号

4.常用操作

(1)字符串编码常用类型

(2)gb2312转为utf-8

(3)转码异常

(4)u'string'指定unicode类型

(5)r'string'禁止转义

(6)字符串转为二进制

(7)二进制转成字符串


1.decode解码

python3后,字符串在Python内部为unicode编码,因此解码为将其他编码转成unicode

(1)语法参数

decode将其他编码的字符串转换成unicode编码

语法:str.decode(encoding='UTF-8',errors='strict')

encoding -- 使用的编码,utf-8,gb2312,cp936,gbk。

errors -- 异常处理方案'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'等

(2)decode例子

#以utf-8编码对unicode对像进行编码

s.decode("utf-8", "ignore") 忽略其中有异常的编码

s.decode("utf-8", "replace") 替换其中异常的编码

#以gb2312编码对字符串str进行解码,以获取unicode u1 = str.decode('gb2312')

2.encode编码

(1)语法参数

encode的作用是将unicode编码转换成其他编码的字符串

语法:str.encode(encoding='UTF-8',errors='strict')

encoding -- 使用的编码,utf-8,gb2312,cp936,gbk。

errors -- 异常处理方案'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace'等

(2)encode例子

str = "this is string example....wow!!!";

print("Encoded String: " + str.encode('base64','strict'))

3.特殊符号

(1)特殊符号介绍

回车符(\r)、换行符(\n)、水平制表符(\t)、垂直制表符(\v)、换页符(\f))    

(2)去掉特殊符号

"   xyz   ".strip()           #去掉前后空格

s.replace('\t','|')    #替换制表符

s.strip('\n') #去掉前后换行符

s.replace("\n", "") #替换换行符 

(3)转义字符

反斜杠是转义字符,必须用两个反斜杠'\\'来表示反斜杠

两个反斜杠就要用四个反斜杠来表示'\\\\'

a=r'F:\百度云同步盘\Buyerid/SmartOmi buyer id &order id 201611.1-2016.12.31.txt'

b=a.replace('\\','/')

4.常用操作

(1)字符串编码常用类型

utf-8,gb2312,cp936,gbk

(2)gb2312转为utf-8

s.decode('gb2312').encode('utf-8')

(3)转码异常

s.decode('gbk', 'ignore').encode('utf-8')

(4)u'string'指定unicode类型

在python2k中u表示unicode string,类型是unicode, 没有u表示byte string,类型是 str。

在python3中所有字符串都是unicode string, u前缀没有特殊含义了。

(5)r'string'禁止转义

字符串前面加r,表示的意思是禁止字符串转义,说明字符串r"XXX"中的XXX是普通字符。

(6)字符串转为二进制

encode用于字符串类型转换为二进制类型

s1='apple'

s2=s1.encode('utf-8')

print(s2)

#b'apple'

(7)二进制转成字符串

s1=b'apple'

s2=s1.decode('utf-8')

猜你喜欢

转载自blog.csdn.net/helunqu2017/article/details/114342674