python3.10.0字符串基础

字符串支持 索引 (下标访问),第一个字符的索引是 0。单字符没有专用的类型,就是长度为一的字符串:

  1. >>> word = 'Python'
  2. >>> word[0] # character in position 0
  3. 'P'
  4. >>> word[5] # character in position 5
  5. 'n'

索引还支持负数,用负数索引时,从右边开始计数:

  1. >>> word[-1] # last character
  2. 'n'
  3. >>> word[-2] # second-last character
  4. 'o'
  5. >>> word[-6]
  6. 'P'

注意,-0 和 0 一样,因此,负数索引从 -1 开始。

除了索引,字符串还支持 切片。索引可以提取单个字符,切片 则提取子字符串:


  1. >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
  2. 'Py'
  3. >>> word[2:5] # characters from position 2 (included) to 5 (excluded)
  4. 'tho'
  5. 切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾:
    
    
    1. >>> word[:2] # character from the beginning to position 2 (excluded)
    2. 'Py'
    3. >>> word[4:] # characters from position 4 (included) to the end
    4. 'on'
    5. >>> word[-2:] # characters from the second-last (included) to the end
    6. 'on'
posted on 2023-01-17 16:42  宇宇小子  阅读(28)  评论(0)    收藏  举报