python学习string method: find and rfind

python 自带的两个查找字符串的方法:find 和rfind.

Python String find() Method

Description:

This method determines if str occurs in string, or in a substring of string if starting index beg and ending index end are given.

 beg 和 end 可以缺省,这样find整个字符串

Syntax:

str.find(str, beg=0 end=len(string))

Parameters:

Here is the detail of parameters:

  • str: specifies the string to be searched.

  • start : starting index, by default its 0

  • end : ending index, by default its equal to the lenght of the string.

Return Value:

It returns index if found and -1 otherwise.输出的index从0开始,和list是一致的,index都是从0开始

Example:

#!/usr/bin/python str1 = "this is string example....wow!!!"; str2 = "exam"; print str1.find(str2); print str1.find(str2, 10); print str1.find(str2, 40);

This will produce following result:

15 15 -1

find 是从左起始查找,对应的从右开始查找的方法是rfind() Method


Description:

This method returns the last index where the substring str is found, or .1 if no such index exists, optionally restricting the search to string[beg:end].

Syntax:

str.rfind(str, beg=0 end=len(string))

Parameters:

Here is the detail of parameters:

  • str: specifies the string to be searched.

  • start : starting index, by default its 0

  • end : ending index, by default its equal to the lenght of the string.

Return Value:

It returns last index if found and -1 otherwise.

Example:

#!/usr/bin/python str = "this is really a string example....wow!!!"; str = "is"; print str.rfind(str); print str.rfind(str, 0, 10); print str.rfind(str, 10, 0); print str.find(str); print str.find(str, 0, 10); print str.find(str, 10, 0);

This will produce following result:

5 5 -1 2 2 -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值