python学习string method: find and rfind

来源:互联网 发布:对于java的理解 编辑:程序博客网 时间:2024/05/17 19:21

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
转载:http://blog.sina.com.cn/s/blog_6e23b2fd010120sb.html
原创粉丝点击