• 字符串


    数据类型

    整数int

    浮点数float

    字符串string

    列表list

    元组tuple

    字典dict

    集合set

    变量

    常量

    Python支持多种数据类型,在计算机内部可以把任意类型看成一个"对象",而变量就是程序中用来指向这些数据对象的,对变量赋值就是把数据和变量关联起来.

    Python的整数没有大小限制,如java中对32位整数限制在-2147483648-2147483647.
    Python的浮点数也没有大小限制,但超出一定范围就表示为inf(无限大).

    特殊方法

    字符串 / 字节序列__repr__、__str__、__format__、__bytes__
    数值转换 __abs__、__bool__、__complex__、__int__、__float__、__hash__、__index__
    集合模拟 __len__、__getitem__、__setitem__、__delitem__、__contains__
    迭代枚举 __iter__、__reversed__、__next__
    可调用模拟 __call__
    上下文管理 __enter__、__exit__
    实例创建和销毁 __new__、__init__、__del__
    属性管理 __getattr__、__getattribute__、__setattr__、__delattr__、__dir__
    属性描述符 __get__、__set__、__delete__
    跟类相关的服务 __prepare__、__instancecheck__、__subclasscheck__
    

    字符串编码

    计算机系统通用的字符编码工作方式:在计算机内存中,统一使用 Unicode 编码,当需要保存到硬盘或者需要传输的时候,就转换为 UTF-8 编码。

    用记事本编辑的时候,从文件读取的 UTF-8 字符被转换为 Unicode 字符到内存里,编辑完成后,保存的时候再把 Unicode 转换为 UTF-8 保存到文件:![字符编码1](D:1 python复习图片字符编码1.jpg)

    浏览网页的时候,服务器会把动态生成的 Unicode 内容转换为 UTF-8 再
    传输到浏览器(网页源码会有<meta charset="UTF-8"/>):![字符编码2](D:1 python复习图片字符编码2.jpg)

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

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

    以 Unicode 表示的 str 通过 encode()方法可以编码为指定的 bytes,相反的bytes通过decode()方法编码成指定的str.

    str 和 bytes 互相转换时,需要指定编码。最常用的编码是 UTF-8。

    设置字符串格式

    精简版%

    >>> format = "Hello, s. s enough for ya?" % %
    >>> values = ('world', 'Hot') 
    >>> format values %
    'Hello, world. Hot enough for ya?' 
    

    完整版format

    # 替换字段没有名称或将索引用作名称
    >>> "{}, {} and {}".format("first", "second", "third") 
    'first, second and third' 
    >>> "{0}, {1} and {2}".format("first", "second", "third") 
    'first, second and third' 
    
    # 索引无需像上面这样按顺序排列
    >>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to") 
    'to be or not to be' 
    
    # 只需向format提供要设置其格式的未命名参数
    >>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3) 
    '3 1 4 2' 
    
    # 通过索引指定相对应的未命名参数
    >>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3) 
    '3 2 4 1' 
    
    """format还有一些(宽度|精度|千位分隔符|符号|对齐|用0填充)用法"""
    

    字符串方法(常用)

    center

    # 方法center通过在两边添加填充字符(默认为空格)让字符串居中。
    >>> "The Middle by Jimmy Eat World".center(39) 
    ' The Middle by Jimmy Eat World ' 
    >>> "The Middle by Jimmy Eat World".center(39, "*") 
    '*****The Middle by Jimmy Eat World*****'
    

    find

    # 方法find在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。
    >>> 'With a moo-moo here, and a moo-moo there'.find('moo') 
    7 
    >>> title = "Monty Python's Flying Circus" 
    >>> title.find('Monty') 
    0 
    >>> title.find('Python')
    6 
    >>> title.find('Flying') 
    15 
    >>> title.find('Zirquss') 
    -1 
    
    >> subject = '$$$ Get rich now!!! $$$' 
    >>> subject.find('$$$') 
    0  # 返回值0并不是布尔值,而是索引
    >>> subject.find('$$$', 1) # 只指定了起点
    20 
    >>> subject.find('!!!') 
    16 
    >>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
    -1
    

    类似的: rfind、index、rindex、count、startswith、endswith

    join

    # join是一个非常重要的字符串方法,其作用与split相反,用于合并序列的元素。
    # 所合并序列的元素必须都是字符串
    
    
    >>> seq = [1, 2, 3, 4, 5] 
    >>> sep = '+' 
    >>> sep.join(seq)  # 尝试合并一个数字列表
    Traceback (most recent call last): 
     File "<stdin>", line 1, in ? 
    TypeError: sequence item 0: expected string, int found 
    >>> seq = ['1', '2', '3', '4', '5'] 
    >>> sep.join(seq)  # 合并一个字符串列表
    '1+2+3+4+5'
    
    
    >>> dirs = '', 'usr', 'bin', 'env' 
    >>> '/'.join(dirs) 
    '/usr/bin/env' 
    
    
    >>> print('C:' + '\'.join(dirs)) 
    C:usrinenv
    

    split

    # split作用与join相反,用于将字符串拆分为序列。
    
    >>> '1+2+3+4+5'.split('+') 
    ['1', '2', '3', '4', '5'] 
    >>> '/usr/bin/env'.split('/') 
    ['', 'usr', 'bin', 'env'] 
    >>> 'Using the default'.split() 
    ['Using', 'the', 'default']
    
    #注意,如果没有指定分隔符,将默认在单个或多个连续的空白字符(空格、制表符、换行符等)处进行拆分。
    

    类似: partition、rpartition、rsplit、splitlines

    lower

    # 方法lower返回字符串的小写版本。
    # 应用场景:将输入与存储的值进行比较时
    
    >>> 'Trondheim Hammer Dance'.lower() 
    'trondheim hammer dance'
    

    类似: islower、istitle、isupper、translate

    capitalize、casefold、swapcase、title、upper

    strip

    # 方法strip将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果。
    
    
    >>> ' internal whitespace is kept '.strip() 
    'internal whitespace is kept' 
    
    # 与lower一样,需要将输入与存储的值进行比较时,strip很有用
    
    #还可在一个字符串参数中指定要删除哪些字符。
    >>> '*** SPAM * for * everyone!!! ***'.strip(' *!') 
    'SPAM * for * everyone' 
    
    # split只删除开头或末尾的指定字符,因此中间的星号未被删除。
    

    类似: lstrip | rstrip

    replace

    # 方法replace将指定子串都替换为另一个字符串,并返回替换后的结果。
    >>> 'This is a test'.replace('is', 'eez') 
    'Theez eez a test'
    

    类似: translate, expandtabs

    判断字符串是否满足特定的条件

    '''
    很多字符串方法都以is打头,如isspace、isdigit和isupper,它们判断字符串是否具有特定
    的性质(如包含的字符全为空白、数字或大写)。如果字符串具备特定的性质,这些方法就返回
    True,否则返回False。
    '''
    

    类似: isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、
    isprintable、isspace、istitle、isupper

  • 相关阅读:
    物理删除文件 业务层
    页面在本机可以显示,其它机器不可以看到页面
    我对asp.net并行请求数量的理解
    分布式缓存Memcached
    任意两个对象赋值,用Spring.Objects.ObjectWrapper效率比直接反射还慢?
    在Linux(RHEL5.5)里用mono2.8.2和jexus4.1运行.net3.5下的MVC2.0过程记录
    Nhibernate连接oracle数据库,主键ID用序列生成时连接数据库IO次数分析
    Sqlserver别太信任SysComments表中的text字段
    .net4.0线程池取消执行的实际应用
    spring.net、castle windsor、unity实现aop、ioc的方式和简单区别
  • 原文地址:https://www.cnblogs.com/kp1995/p/10315495.html
Copyright © 2020-2023  润新知