Python Coding Reference: index() and find() for string (substrin

  • 时间:2020-09-17 14:26:24
  • 分类:网络文摘
  • 阅读:84 次

How to Find the Index of Given Element in String/Tuple/List in Python?

The index() in Python gives the lowest index that element matches the target. The index starts at zero – where the first element is at index 0. The syntax is:

1
2
3
string.index(target)
[list].index(target)
(tuple).index(target)
string.index(target)
[list].index(target)
(tuple).index(target)

As we can see, index() can be applied to both string, tuple and list. For example:

1
2
3
"abcde".index("b") # 1
["a","b","c","d","e"].index("b") # 1
("a","b","c","d","e").index("b") # 1
"abcde".index("b") # 1
["a","b","c","d","e"].index("b") # 1
("a","b","c","d","e").index("b") # 1

If the element is not in the list, string or tuple, a ValueError will the thrown. For example:

1
2
3
4
5
6
>>> "find me".index("aaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
</module>
>>> "find me".index("aaa")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>
</module>

Therefore, it is often recommended to use index() if you are more likely to be sure that the substring exists or element appears in the tuple/list.

The find() in Python: Finding substring

The string object has a find() method which looks for the first appeared substring(). The Syntax is:

1
"string".find(substring)
"string".find(substring)

For example,

1
"abc".find("b") # 1
"abc".find("b") # 1

If the substring is not in the string, then a -1 will be returned without errors.

1
"abc".find("bac") # -1
"abc".find("bac") # -1

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
餐饮020 新开餐厅微信微博营销四段法  如何实现微博的有效营销呢?  微博营销怎么做?看这篇就行了  微博营销如何赚钱?我给大家提供一些思路  百度AI生态的建立 给创业公司带来了什么好处?  创业项目营销效果不佳 只因没做好这几件事  AI把英语系新生吓退学?别急,我们从来都是那只懒蚂蚁  创业初期该做什么?首先你需要避开的这5大坑!  2018世界人工智能大会开幕,它给创业者带来了哪些思路?  创业寒冬下 初创公司如何才可以打破C轮死魔咒? 
评论列表
添加评论