• Python



    字符串是不可变类型,改变一个字符串的元素需要新建一个字符串。

    1. 字符串和操作符

    1.1 序列操作符切片

    • 删除一个字符串
    >>> a = 'astring'
    >>> del a
    >>> a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    
    • 虽然开始和结束索引值可以超过序列的长度,但直接取某个越界的值作为索引不被允许的。
    >>> a = '0123456'
    >>> a[-10:10]
    '0123456'
    >>> a[:10]
    '0123456'
    >>> a[10]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: string index out of range
    
    • 成员操作符(in,not in)
      1)成员操作符用于判断一个字符或者子串(中的字符)是否出现在领一个字符串中。
      2)find() 或者 index() 函数用来判断一个字符串是否包含另一个字符串。

    Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

    符串中是否包含子字符串 str ,如果指定 beg(开始) 检查是否包含在指定范围内,如果包含子字符串返回开始
    
    语法
    find()方法语法:
    str.find(str, beg=0, end=len(string))
    
    参数
    str -- 指定检索的字符串
    beg -- 开始索引,默认为0。
    end -- 结束索引,默认为字符串的长度。
    
    返回值
    如果包含子字符串返回开始的索引值,否则返回-1。
    
    实例(Python 2.0+)
    >>>info = 'abca'
    >>> print info.find('a')    
    #从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
    0
    
    >>> print info.find('a',1) 
    #从下标1开始,查找在字符串里第一个出现的子串:返回结果3
    3
    
    >>> print info.find('3')    
    # 查找不到返回-1
    -1
    
    

    Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

    实例(Python 2.0+)
    #!/usr/bin/python
     
    str1 = "this is string example....wow!!!";
    str2 = "exam";
     
    print str1.index(str2);
    print str1.index(str2, 10);
    print str1.index(str2, 40);
    
    以上实例输出结果如下:
    15
    15
    Traceback (most recent call last):
      File "test.py", line 8, in 
      print str1.index(str2, 40);
    ValueError: substring not found
    
    shell returned 1
    
    • 连接符(+)

    Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

    语法
    join()方法语法:
    str.join(sequence)
    
    参数
    sequence -- 要连接的元素序列。
    
    返回值
    返回通过指定字符连接序列中元素后生成的新字符串。
    
    实例(Python 2.0+)
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    str = "-";
    seq = ("a", "b", "c"); # 字符串序列
    print str.join( seq );
    
    以上实例输出结果如下:
    a-b-c
    

    2. 内建函数

    cmp()

    同比较操作符一样,内建的cmp()函数也根据字符串的ASCII码值进行比较。

    cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
    
    >>> str1 = 'abc'
    >>> str2 = 'lmn'
    >>> str3 = 'xyz'
    >>> cmp(str1,str2)
    -1
    >>> cmp(str3,str1)
    1
    >>> cmp(str2,'lmn')
    0
    
    

    min() 和 max()

    返回最小或最大的字符(按照ASCII码值排列)

    >>> min('ab12cd')
    '1'
    >>> min('ABabCDcd')
    'A'
    
    

    enumerate()

    enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

    >>> s = 'abcdef'
    >>> for i,t in enumerate(s):
    ...     print i,t
    ... 
    0 a
    1 b
    2 c
    3 d
    4 e
    5 f
    
    
    语法
    以下是 enumerate() 方法的语法:
    enumerate(sequence, [start=0])
    
    参数
    sequence -- 一个序列、迭代器或其他支持迭代对象。
    start -- 下标起始位置。
    
    返回值
    返回 enumerate(枚举) 对象。
    
    实例
    >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
    >>> list(enumerate(seasons))
    [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
    >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
    [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
    
    

    ZIP()

    zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

    如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

    zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。

    语法
    zip 语法:
    zip([iterable, ...])
    
    参数说明:
    iterabl -- 一个或多个迭代器;
    
    返回值
    返回元组列表。
    
    实例
    >>>a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [4,5,6,7,8]
    >>> zipped = zip(a,b)     # 打包为元组的列表
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(a,c)              # 元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
    [(1, 2, 3), (4, 5, 6)]
    

    chr()、unichr() 和 ord()

    chr() 函数用一个范围在 range(256) 内的(就是0~255)整数作为参数,返回一个对应的字符。unichr()跟它一样,只不过返回的是 Unicode 字符。
    ord() 函数以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

    >>> chr(65)
    'A'
    >>> ord('a')
    97
    

    3. 字符串的独特特性

    3.1 三引号

    Python 的三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其它特殊字符。

    >>> hi = '''hi
    ... there'''
    >>> hi
    'hi
    there'
    >>> print hi
    hi
    there
    

    3.2 字符串不变性

    字符串是一种不可变的数据类型,它的值不能被改变或修改。这就意味着如果想修改一个字符串,或者截取一个子串,或者在字符串的末尾连接另一个字符串等等,必须新建一个字符串。
    这听起来要比实际情况复杂。因为Python 替你管理内存,你根本不需要知道到底发生了什么,每次你修改一个字符串或者做一些改变字符串内容的操作时,Python 都会自动为你分配一个新串。在下面的例子里面,Python 分别为"abc"和"def"分配了空间,当进行连接操作时,Python 自动为新的字符串"abcdef"分配了空间。

    >>> 'abc' + 'def'
    'abcdef'
    

    给变量赋值没什么不同

    >>> s = 'abc'
    >>> s = s + 'def'
    >>> s
    'abcdef'
    

    在上面的例子里,看起来是我们先把 abc 赋给了 s,然后在 s 末尾添加了“def”。这样看起来字符串似乎是可变的,其实事实是在“s + 'def'”这个操作进行的时候,新建了一个字符串,然后这个新的对象被赋给了s,原来的字符串 'abc' 被释放掉了。
    我们可以用id()函数来看一下,id()函数返回一个对象的身份,是一个整数。CPython 中 id() 函数用于获取对象的内存地址。

    >>> s = 'abc'
    >>> id(s)
    140058835478368
    >>> 
    >>> s += 'def'
    >>> id(s)
    140058834819904
    

    注意修改前后的身份是不同的。另外,字符串的一个字符或者一片字符的改动都是不被允许的。

    >>> s = 'abcdef'
    >>> s[2] = 'C'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    >>> s[3:6] = 'DEF'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment
    
    

    两个操作都抛出了异常。

    >>> s = 'abcdef'
    >>> s = '%sC%s' % (s[0:2],s[3:])
    >>> s
    'abCdef'
    >>> 
    >>> s[0:3] + 'DEF'
    'abCDEF'
    >>> 
    

    上面的例子可以看出,对像字符串这样的不可变对象,左值必须是一个完整的对象,对赋值操作的右值没有这个限制。

    [参考文献]

    1. 《Python 核心编程(第二版)》
    2. Python find()方法 https://www.runoob.com/python/att-string-find.html
    3. Python index()方法 https://www.runoob.com/python/att-string-index.html
    4. Python join()方法 https://www.runoob.com/python/att-string-join.html
    5. Python cmp()方法 https://www.runoob.com/python/func-number-cmp.html
    6. Python enumerate()方法 https://www.runoob.com/python/python-func-enumerate.html
    7. Python zip()方法 https://www.runoob.com/python/python-func-zip.html
    8. Python id()函数 https://www.runoob.com/python/python-func-id.html
  • 相关阅读:
    QString 与 string转换
    Lua 判断表是否为空方法
    QT 继承QWidget && 继承QDialog
    QNetworkAccessManager
    Lua语言特色
    Lua逻辑操作符
    Lua语言总结
    Lua 函数
    Lua数据类型
    QT 通过QNetworkReply *获取对应请求的URL地址
  • 原文地址:https://www.cnblogs.com/sxiszero/p/12500521.html
Copyright © 2020-2023  润新知