您的位置:首页 > 编程语言 > Python开发

Python中的字符串索引基本知识

2017-03-20 09:51 204 查看
Strings can be indexed (subscripted),
with the first character having index 0. There is no separate character type; a character is simply a string of size one:

>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'

Indices may also be negative numbers, to start counting from the right:

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


Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:

>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'Note how the start is always included, and the end always excluded.
This makes sure that 
s[:i] + s[i:]
 is
always equal to 
s
:

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second
index defaults to the size of the string being sliced.

>>> 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 strings cannot be changed — they are immutable.
Therefore, assigning to an indexed position in the string results in an error:
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment


The built-in function 
len()
 returns
the length of a string:


>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程语言 索引