教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 什么是Python的字符串

什么是Python的字符串

发布时间:2021-12-29   编辑:jiaochengji.com
教程集为您提供什么是Python的字符串等资源,欢迎您收藏本站,我们将为您提供最新的什么是Python的字符串资源

对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符:

<pre class="brush:php;toolbar:false">>>> ord('A') 65 >>> ord('中') 20013 >>> chr(66) 'B' >>> chr(25991) '文'</pre>

如果知道字符的整数编码,还可以用十六进制这么写str:

<pre class="brush:php;toolbar:false">>>> '\u4e2d\u6587' '中文'</pre>

两种写法完全是等价的。

由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes。

Python对bytes类型的数据用带b前缀的单引号或双引号表示:

<pre class="brush:php;toolbar:false">x = b'ABC'</pre>

要注意区分'ABC'和b'ABC',前者是str,后者虽然内容显示得和前者一样,但bytes的每个字符都只占用一个字节。

相关推荐:《Python视频教程》

以Unicode表示的str通过encode()方法可以编码为指定的bytes,例如:

<pre class="brush:php;toolbar:false">>>> 'ABC'.encode('ascii') b'ABC' >>> '中文'.encode('utf-8') b'\xe4\xb8\xad\xe6\x96\x87' >>> '中文'.encode('ascii') Traceback (most recent call last):   File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)</pre>

纯英文的str可以用ASCII编码为bytes,内容是一样的,含有中文的str可以用UTF-8编码为bytes。含有中文的str无法用ASCII编码,因为中文编码的范围超过了ASCII编码的范围,Python会报错。

在bytes中,无法显示为ASCII字符的字节,用\x##显示。

反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:

<pre class="brush:php;toolbar:false">>>> b'ABC'.decode('ascii') 'ABC' >>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8') '中文'</pre>

如果bytes中包含无法解码的字节,decode()方法会报错:

<pre class="brush:php;toolbar:false">>>> b'\xe4\xb8\xad\xff'.decode('utf-8') Traceback (most recent call last):   ... UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 3: invalid start byte</pre>

如果bytes中只有一小部分无效的字节,可以传入errors='ignore'忽略错误的字节:

<pre class="brush:php;toolbar:false">>>> b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore') '中'</pre>

要计算str包含多少个字符,可以用len()函数:

<pre class="brush:php;toolbar:false">>>> len('ABC') 3 >>> len('中文') 2</pre>

len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数:

<pre class="brush:php;toolbar:false">>>> len(b'ABC') 3 >>> len(b'\xe4\xb8\xad\xe6\x96\x87') 6 >>> len('中文'.encode('utf-8')) 6</pre>

可见,1个中文字符经过UTF-8编码后通常会占用3个字节,而1个英文字符只占用1个字节。

您可能感兴趣的文章:
python中r代表什么意思
python正则表达式r表示什么意思
string在python中是什么意思
python中转义字符是什么意思
python u是什么意思
r在python中表示什么意思
python中len是什么
python文件为什么加utf-8
python中%s是什么
a[1:]在python什么意思

[关闭]
~ ~