小伙不帅

博客园 首页 新随笔 联系 订阅 管理

第一个字符索引是 0。单个字符并没有特殊的类型,只是一个长度为一的字符串:

索引页可以用负数,用负数的话索引是有右边开始的,同时索引从-1开始,

注意: 0和-0是一样的

word = 'Python'

>>> word[0] # 字符串的位置 0

'P'

>>> word[5]字符串的位置 5

'n'

>>> word[-1]  # 最后一个字符
'n'
>>> word[-2]  # 倒数第二的字符
'o'
>>> word[-6]
'P'

字符串切片,字符串切片特性:顾头不顾尾
word = 'Python'
word[0:]从头切到尾
word[:]从头切到位
切片的索引有默认值;省略开始索引时默认为0,省略结束索引时默认为到字符串的结束
>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'


'Python'
word[2:5]从索引为2的位置开始切到第5个位置,不包括第5个元素

注意切片的开始总是被包括在结果中,而结束不被包括。这使得 s[:i] s[i:] 总是等于 s
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
 


 

posted on 2019-08-01 16:47  小伙不帅  阅读(390)  评论(0编辑  收藏  举报