• Python学习记录(三)--字符串


    1、字符串基础 P62
      字符串是不可变的
      字符串是不可变的

      >>> str='website'
      >>> str[-2:]='yilia'
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: 'str' object does not support item assignment

    2、字符串格式化 : % %s %.3f

      >>> a = 'hello %s, %s'
      >>> b = ('world', 'hello')

      >>> a % b
      'hello world, hello'

    3、字符串方法

      (1)find :在一个较长的字符串中查找一个字符串,返回子字符串的首字母索引
        >>> str = 'who are you ? i am a strudent'
        >>> str.find("you")
        8

        >>> str.find("a", 2, -1) #提供起点和结束点
        4
        >>> str.find("a", 8, -1)
        16

      (2) join: 在队列中添加元素
        >>> str = ['I', 'AM', 'YILIA']
        >>> seq='+'
        >>> str.join(seq)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        AttributeError: 'list' object has no attribute 'join'
        >>> str = list(str)
        >>> str.join(seq)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        AttributeError: 'list' object has no attribute 'join'
        >>> str2 = ['a', 'b', 'c']
        >>> str2.join(seq)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        AttributeError: 'list' object has no attribute 'join'
        >>> str3 = 'a', 'b', 'c', 'dd'
        >>> str3.join(seq)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        AttributeError: 'tuple' object has no attribute 'join'
        >>> seq.join(str2)
        'a+b+c'
        >>> seq.join(str3)
        'a+b+c+dd'

      (3) lower: 返回字符串的小写字母
        >>> 'I AM YILIA'.lower()
        'i am yilia'

        其它: upper、 islower、 isupper、 capitalize、 swapcase ...

      (4) replace: 返回字符串的所有匹配想均被替换后的字符串, 原字符串不变
        >>> str = 'i am amli'
        >>> str.replace("am", 'yi')
        'i yi yili'
        >>> str
        'i am amli'

      (5) split: 将字符串分割成序列
        >>> str
        'i am amli'
        >>> str.split('a')
        ['i ', 'm ', 'mli']

      (6) strip: 去除字符串两侧的空格(不包含内部), 返回新字符串,原字符串不变
        >>> str = ' i am yilia '
        >>> str.strip()
        'i am yilia'
        >>> str
        ' i am yilia '

      (7) translate: 替换字符串中的单个字符,可同时替换多个

  • 相关阅读:
    现实世界的Windows Azure:采访Gridsum的Sr.业务发展总监Yun Xu
    现在可用——Windows Azure SDK 1.6
    Rock Paper Azure Challenge回来啦
    这几天比较忙,自己的职业生涯规划好了吗?目标又是什么呢?生活在十字路口。。。。。。
    GDI+ 学习记录(24): 输出文本<3>
    GDI+ 学习记录(30): MetaFile 文件操作
    GDI+ 学习记录(29): 区域 Region
    GDI+ 学习记录(26): 显示图像 Image
    GDI+ 学习记录(25): 变换 Transform
    返回整数的四种情况
  • 原文地址:https://www.cnblogs.com/songshu-yilia/p/5235845.html
Copyright © 2020-2023  润新知