《Dive into python3》:Chapter 4 String(字符串)

这一章节主要内容是:字符编码Unicode的一些知识、格式化字符串以及其它常用的字符串方法。

一、字符编码

        屏幕上的每一块文本都是以某种字符编码(character encoding)方式保存的,不同的编码方式i可能会使用不同的字节序列:大端模式(big-endian)或小端模式(little-endian)。编码方式是将计算机可读的数字映射成人类可读的字符的解码密钥。

         unicode编码系统为表达任意语言的任意字符而设计。它使用4字节的数字来表达mei'每个字母、符号,或者表意文字(ideograph)。在空间效率上,UTF-16比UTF-32高两倍。为了解决字节序问题,"byte-order mark",UTF-8是可变长编码系统。

  字节 表示范围
UTF-32 4  
UTF-16 2 0-65535
UTF-8 1 0-127

二、格式化字符串format()方法的使用

humansize.py
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}

def approximate_size(size, a_kilobyte_is_1024_bytes=True):
    '''Convert a file size to human-readable form.

    Keyword arguments:
    size -- file size in bytes
    a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
                                if False, use multiples of 1000

    Returns: string

    '''
    if size < 0:
        raise ValueError('number must be non-negative')

    multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
    for suffix in SUFFIXES[multiple]:
        size /= multiple
        if size < multiple:
            return '{0:.1f} {1}'.format(size, suffix)   '{0:.1f}和{1}里面的0和1是format()参数索引,返回值为格式化后的字符串'

    raise ValueError('number too large')

if __name__ == '__main__':
    print(approximate_size(1000000000000, False))
    print(approximate_size(1025))

>>> 
======== RESTART: F:\python3\wq\diveintopython3\examples\humansize.py ========
1.0 TB
1.0 KiB
>>> 

复杂一点的使用复合字段名:格式说明符通过使用类似python语法访问到对象元素或属性。关于格式说明符参考:http://docs.python.org/3.1/library/string.html#format-specification-mini-language

三、string vs bytes

字节即字节;字符是一种抽象。一个不可变 (immutable) 的Unicode 编码的字符序列叫做 string 。一串由 0 到 255 之间的数字组成的序列叫做 bytes 对象。使用 “byte 字面值 ” 语法 b'' 来定义 bytes 对象。 byte 字面值里的每个字节可以是 ASCII 字符或者是从 \x00 到 \xff 编码了的 16 进制数。 

补充内容:python2源码默认编码方式是ASCII,python3的默认编码方式是UTF-8.如需使用其他编码格式,只要在文件首行或第二行声明即可,声明格式:# ‐*‐ coding: windows‐1252 ‐*‐

猜你喜欢

转载自blog.csdn.net/qq_38576427/article/details/81734891