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: 替换字符串中的单个字符,可同时替换多个

posted @ 2016-03-02 17:37  松鼠的松子  阅读(763)  评论(0编辑  收藏  举报