共計 536 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用以下方法獲取列表、元組和字符串的索引值:
- 列表和元組:使用
index()
方法來獲取元素的索引值。例如:
my_list = [10, 20, 30, 40]
index = my_list.index(30)
print(index) # 輸出:2
- 字符串:可以使用
index()
方法來獲取子字符串的索引值。例如:
my_string = "Hello, World!"
index = my_string.index("World")
print(index) # 輸出:7
如果要查找的元素或子字符串不存在,以上方法會引發(fā) ValueError
異常。如果要避免這種情況,可以使用 in
運算符來檢查元素或子字符串是否存在于列表、元組或字符串中。例如:
my_list = [10, 20, 30, 40]
if 30 in my_list:
index = my_list.index(30)
print(index) # 輸出:2
else:
print(" 元素不存在 ")
my_string = "Hello, World!"
if "World" in my_string:
index = my_string.index("World")
print(index) # 輸出:7
else:
print(" 子字符串不存在 ")
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完