python字符串find_Python字符串find()

python字符串find

Python String find() method is used to find the index of a substring in a string.

Python String find()方法用于查找字符串中子字符串的索引。

Python字符串find() (Python String find())

The syntax of find() function is:

find()函数的语法为:

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

This function returns the lowest index in the string where substring “sub” is found within the slice s[start:end].

此函数返回在切片 s [start:end]中找到子字符串“ sub”的字符串中的最低索引。

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

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

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

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

If the substring is not found then -1 is returned.

如果未找到子字符串,则返回-1。

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

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

Python字符串find()示例 (Python String find() examples)

Let’s look at some simple examples of find() method.

让我们看一下find()方法的一些简单示例。

s = 'abcd1234dcba'

print(s.find('a'))  # 0
print(s.find('cd'))  # 2
print(s.find('1', 0, 5))  # 4
print(s.find('1', 0, 2))  # -1

Python字符串rfind() (Python String rfind())

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

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

s = 'abcd1234dcba'

print(s.rfind('a'))  # 11
print(s.rfind('a', 0, 20))  # 11
print(s.rfind('cd'))  # 2
print(s.rfind('1', 0, 5))  # 4
print(s.rfind('1', 0, 2))  # -1

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

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

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

def find_all_indexes(input_str, search_str):
    l1 = []
    length = len(input_str)
    index = 0
    while index < length:
        i = input_str.find(search_str, index)
        if i == -1:
            return l1
        l1.append(i)
        index = i + 1
    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脚本和更多Python示例。

Reference: str.find()

参考: str.find()

翻译自: https://www.journaldev.com/23666/python-string-find

python字符串find

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值