zoukankan      html  css  js  c++  java
  • Python的字符串

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

    >>> ord('A')
    65
    >>> ord('中')
    20013
    >>> chr(66)
    'B'
    >>> chr(25991)
    '文'

    由于Python的字符串类型是str,在内存中以Unicode表示,一个字符对应若干个字节。

    1、如果要在网络上传输,或者保存到磁盘上,就需要把str变为以字节为单位的bytes

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

    x = b'ABC'
    

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

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

    >>> 'ABC'.encode('ascii')
    b'ABC'
    >>> '中文'.encode('utf-8')
    b'xe4xb8xadxe6x96x87'
    >>> '中文'.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)
    

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

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

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

    >>> b'ABC'.decode('ascii')
    'ABC'
    >>> b'xe4xb8xadxe6x96x87'.decode('utf-8')
    '中文'
    

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

    >>> b'xe4xb8xadxff'.decode('utf-8')
    Traceback (most recent call last):
      ...
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 3: invalid start byte
    

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

    >>> b'xe4xb8xadxff'.decode('utf-8', errors='ignore')
    '中'
    

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

    >>> len('ABC')
    3
    >>> len('中文')
    2
    

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

    >>> len(b'ABC')
    3
    >>> len(b'xe4xb8xadxe6x96x87')
    6
    >>> len('中文'.encode('utf-8'))
    6
    

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


    https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431664106267f12e9bef7ee14cf6a8776a479bdec9b9000
  • 相关阅读:
    如何让我domain里的机器都跟domain controller的时间保持一致?
    [PowerShell Utils] Create a list of virtual machines based on configuration read from a CSV file in Hyper-V
    Reboot server stuck at “Press ESC in 1 seconds to skip startup.nsh”
    [PowerShell Utils] Remotely install Hyper-V and Failover Cluster feature on a list of windows 2012 servers
    [PowerShell Utils] Automatically Change DNS and then Join Domain
    SharePoint 2016 IT Preview的新feature列表
    LeetCode Permutations问题详解
    Rotate Image 旋转图像
    单链表的快速排序(转)
    anagrams 查找序列里具有相同字符但顺序不同的单词
  • 原文地址:https://www.cnblogs.com/gkh-whu/p/10244683.html
Copyright © 2011-2022 走看看