zoukankan      html  css  js  c++  java
  • 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: 替换字符串中的单个字符,可同时替换多个

  • 相关阅读:
    2019沈阳网路赛 D. Fish eating fruit (点分治)
    2019南京网路赛 A.The beautiful values of the palace (主席树)
    洛谷 P2634 [国家集训队]聪聪可可(点分治)
    AcWing252 树 (点分治模板题)
    点分治模板 (洛谷 P3806)
    2020牛客寒假算法基础集训营2 J-求函数(线段树维护矩阵乘法)
    七夕祭(贪心+中位数)
    数据结构-集合
    数据结构-广义表
    数据结构-稀疏矩阵
  • 原文地址:https://www.cnblogs.com/songshu-yilia/p/5235845.html
Copyright © 2011-2022 走看看