What is the method for obtaining index values in Python?

In Python, you can use the following methods to obtain the index values of lists, tuples, and strings:

  1. find()
my_list = [10, 20, 30, 40]
index = my_list.index(30)
print(index)  # 输出:2
  1. find()
my_string = "Hello, World!"
index = my_string.index("World")
print(index)  # 输出:7

If the element or substring being searched for does not exist, the above method will raise a ValueError exception. To avoid this situation, you can use the ‘in’ operator to check if the element or substring exists in the list, tuple, or string. For example:

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("子字符串不存在")
bannerAds