Python字符串index()

Python String index() function returns the lowest index where the specified substring is found. If the substring is not found then ValueError is raised.

Python String index()函数返回找到指定子字符串的最低索引。 如果未找到子字符串,则引发ValueError

Python字符串index()语法 (Python String index() syntax)

This function syntax is:

该函数语法为:

str.index(sub[, start[, end]])

The start parameter default value is 0 and it’s an optional argument.

起始参数的默认值为0,它是一个可选参数。

The end argument default value is length of the string, it’s an optional argument.

end参数的默认值是字符串的长度,它是一个可选参数。

We should use the index() function when we want to know the index position of the substring. For checking if a substring is present, we can use in operator.

当我们想知道子字符串的索引位置时,应该使用index()函数。 为了检查是否存在子字符串,我们可以使用in运算符。

Python字符串索引()与查找() (Python string index() vs find())

Python string index() function raises ValueError if substring is not found whereas find() function returns -1. This is the only difference between these functions.

如果未找到子字符串,Python字符串index()函数将引发ValueError,而find()函数将返回-1。 这是这些功能之间的唯一区别。

Python String index()示例 (Python String index() examples)

Let’s look at some simple examples of index() function.

让我们看一下index()函数的一些简单示例。

s = 'abcd1234dcba'

print(s.index('a'))
print(s.index('cd'))
print(s.index('1', 0, 5))

Output:

输出:

0
2
4

Now let’s look at another example where the substring is not present and ValueError is thrown. I will use a try-except block to catch the exception and print its message.

现在让我们看另一个不存在子字符串并且引发ValueError的示例。 我将使用try-except块来捕获异常并打印其消息。

s = 'abcd1234dcba'

try:
    print(s.index('1', 0, 2))
except ValueError as ve:
    print(ve)

Output: substring not found

输出: substring not found

Python字符串rindex() (Python String rindex())

Python string rindex() method is similar to index(), except that search is performed from right to left.

Python字符串rindex()方法类似于index(),不同之处在于搜索是从右到左执行的。

s = 'abcd1234dcba'

print(s.rindex('a'))
print(s.rindex('cd'))
print(s.rindex('1', 0, 5))

try:
    print(s.rindex('1', 0, 2))
except ValueError as ve:
    print(f'Error Message = {ve}')

Output:

输出:

11
2
4
Error Message = substring not found

使用index()查找子字符串的所有索引 (Find all indexes for substring using index())

Python string index() method returns the first matched index. We can define a custom function to find all the indexes where the substring is found.

Python字符串index()方法返回第一个匹配的索引。 我们可以定义一个自定义函数,以查找找到子字符串的所有索引。

def find_all_indexes(input_str, search_str):
    l1 = []
    length = len(input_str)
    position = 0
    while position < length:
        try:
            i = input_str.index(search_str, position)
            l1.append(i)
            position = i + 1
        except ValueError as ve1:
            # finally exception will be raised because all the indexes are found
            return l1


s = 'abaacdaa12aa2'
print(find_all_indexes(s, 'a'))
print(find_all_indexes(s, 'aa'))

Output:

输出:

[0, 2, 3, 6, 7, 10, 11]
[2, 6, 10]
GitHub Repository. GitHub存储库中检出Python脚本和更多字符串示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/23992/python-string-index

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值