• Python的字符串操作和Unicode


    字符串类型

    str:Unicode字符串。采用''或者r''构造的字符串均为str,单引号可以用双引号或者三引号来代替。无论用哪种方式进行制定,在Python内部存储时没有区别。
    bytes:二进制字符串。由于jpg等其他格式的文件不能用str进行显示,所以才用bytes来表示,bytes的每个字节为一个0-255的数字。如果打印的时候,Python会把能够用ASCII表示的部分显示为ASCII,这样方便阅读。bytes几乎支持除了格式化以外的所有str的方法,甚至包括了re模块
    bytearray():二进制可原地变动的字符串。

    utf-8编码范围

    范围 字节数 存储格式
    0x0000~0x007F (0 ~ 127) 1字节 0xxxxxxx
    0x0080~0x07FF(128 ~ 2047) 2字节 110xxxxx 10xxxxxx
    0x0800~FFFF(2048 ~ 65535) 3字节 1110xxxx 10xxxxxx 10xxxxxx
    0x10000~1FFFFFF(65536 ~ 2097152) 4字节 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    0x2000000~0x3FFFFFF 5字节 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    0x4000000~0x7FFFFFFF) 6字节 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

    字节顺序标记BOM

    BOM是byte order marker的缩写,

    指定编码写入时的规则

    Python在使用'utf-8'编码写入文件时不会写入BOM头,但是如果指定编码'utf-8-sig'则会迫使Python写入一个BOM头。
    使用'utf-16-be'不会写入一个BOM头,但是采用'utf-16'则会写入一个BOM头。

    >>> open('h.txt','w',encoding='utf-8-sig').write('aaa')
    3
    >>> open('h.txt','rb').read()
    b'xefxbbxbfaaa'
    >>> open('h.txt','w',encoding='utf-16').write('bbb')
    3
    >>> open('h.txt','rb').read()
    b'xffxfebx00bx00bx00'
    >>> open('hh.txt','w',encoding='utf-16-be').write('ccc')
    3
    >>> open('hh.txt','rb').read()
    b'x00cx00cx00c'
    >>> open('h.txt','w',encoding='utf-8').write('ddd')
    3
    >>> open('h.txt','rb').read()
    b'ddd'
    

    读取时的规则

    如果指定了正确的编码,那么BOM会忽略,否则BOM会显示为乱码或者返回异常。

    >>> open('h.txt','r').read()
    '锘縟dd'
    >>> open('h.txt','r',encoding='utf-8-sig').read()
    'ddd'
    

    编码与解码

    • chr和ord
    >>> ord('中')         #20013
    >>> chr(20013)        #'中'
    
    • 把Unicode硬编码进字符串中。
      'xhh':用2位十六进制来表示一个字符
      'uhhhh':用4位十六进制来表示一个字符:
      'Uhhhhhhhh':用8位十六进制来表示一个字符
      >>> s = 'pyx74hu4e2don' #'pyth中on'

    str和bytes, bytearray进行转换

    str.encode(encoding='utf-8')
    bytes(s,encoding='utf-8')
    bytes.decode(encoding='utf-8')
    str(B, encoding='utf-8')
    bytearray(string, encoding='utf-8')
    bytearray(bytes)

    文档编码声明

    Python默认使用utf-8编码。
    # -*- coding: latin-1 -*-:表示声明文档为latin-1编码。

    帮助函数

    sys.platform					#'win32'
    sys.getdefaultencoding() 		# 'utf-8'
    sys.byteorder					#'little'
    s.isalnum()                     #s表示字符串
    s.isalpha()
    s.isdecimal
    s.isdigit()
    s.isnumeric()
    s.isprintable()
    s.isspace()
    s.isidentifier()                #如果字符串可以用作变量名,那么返回True
    s.islower()
    s.isupper()
    s.istitle()
    
  • 相关阅读:
    [JSOI2008]最小生成树计数
    [SCOI2009]windy数
    Sql Server 存储过程
    Sql Server 表操作
    .NET WebService中使用 Session
    从头入手jenkins
    swiftlint 你所要知道的所有!!
    swiftlint swift代码规范检查神器
    使用RxSwift 实现登录页面的条件绑定
    iOS 设置不同环境下的配置 Debug Release 生产 测试 等等
  • 原文地址:https://www.cnblogs.com/jessonluo/p/4744833.html
Copyright © 2020-2023  润新知