Python字符串的索引與切片
1、字符串的索引與獲取
字符串的索引方式與列表的索引方式是一樣的。只不過列表是每個元素的自身就有一個索引位置,而字符串是每個字符就有一個索引位置。
- 索引規(guī)則與列表相同
- 切片和索引的獲取與列表相同
- 無法通過索引進行修改和刪除操作(字符串不可修改)
示例如下:
name = 'Adem' print(name[0]) print(name[-1])
執(zhí)行結果如下:
>>> A
>>> m
2、字符串的 find 與 index 函數(shù)
find 與 index 函數(shù)的功能:獲取元素的索引位置
find 與 index 函數(shù)的用法:
- string.index(item) —> item:查詢個數(shù)的元素,返回索引位置
- string.find(item) —> item:查詢個數(shù)的元素,返回索引位置
find 與 index 函數(shù)的區(qū)別:
- find 如果獲取不到,返回 -1
- index 如果獲取不到,則直接報錯
示例如下:
info = 'My name is Neo' print(info.find('Neo')) print(info.index('Neo'))
執(zhí)行結果如下:
>>> 11
>>> 11
info = 'My name is Neo' print(info.find('Jack')) print(info.index('Jack'))
執(zhí)行結果如下:
>>> -1
>>> ValueError: substring not found
到此這篇關于Python字符串的索引與切片的文章就介紹到這了,更多相關Python索引與切片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章

python使用pyhook監(jiān)控鍵盤并實現(xiàn)切換歌曲的功能

淺談Keras中fit()和fit_generator()的區(qū)別及其參數(shù)的坑