日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python字符串的索引與切片_python

作者:渴望力量的哈士奇 ? 更新時間: 2022-06-09 編程語言

1、字符串的索引與獲取

字符串的索引方式與列表的索引方式是一樣的。只不過列表是每個元素的自身就有一個索引位置,而字符串是每個字符就有一個索引位置。

  • 索引規則與列表相同
  • 切片和索引的獲取與列表相同
  • 無法通過索引進行修改和刪除操作(字符串不可修改)

示例如下:

name = 'Adem'
print(name[0])
print(name[-1])

?執行結果如下:

?>>> A
>>> m

2、字符串的 find 與 index 函數

find 與 index 函數的功能:獲取元素的索引位置

find 與 index 函數的用法:

  • string.index(item) —> item:查詢個數的元素,返回索引位置
  • string.find(item) —> item:查詢個數的元素,返回索引位置

find 與 index 函數的區別:

  • find 如果獲取不到,返回 -1
  • index 如果獲取不到,則直接報錯

示例如下:

info = 'My name is Neo'
print(info.find('Neo'))
print(info.index('Neo'))

執行結果如下:

>>> 11
?>>> 11

info = 'My name is Neo'
print(info.find('Jack'))
print(info.index('Jack'))

執行結果如下:

>>> -1
>>> ValueError: substring not found

原文鏈接:https://blog.csdn.net/weixin_42250835/article/details/123153592

欄目分類
最近更新