python判斷一個字串是否為另一字串的子串的幾種方法
字串型別是Python裡面最常見的型別。在處理字串的時候經常會用到string模組,string模組的方法是在Python1.6裡面新增進來的。本文中主要以string模組的方法來判斷一個字串是否為另一字串的子串。
(一)首先介紹一種最簡單的方法:成員操作 in
ss=raw_input('Enter a short sequence:')
ls=raw_input('Enter a long sequence:')
print ss in ls
如果短字串ss是長字串ls的子字串,則輸出True
(二)第二種方法用到string模組的find()方法
import string ss=raw_input('Enter a short sequence:') ls=raw_input('Enter a long sequence:') if(string.find(ls,ss)!=-1): print 'find it' else: print 'fail'
用help(string.find)可看到關於find()方法的描述:
Help on function find in module string:
find(s, *args)
find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
string模組的find()方法常用於輸出子字串的索引,若不是子字串就返回-1。於是在這裡可以用來判斷一個字串是否為另一字串的子串。
(三)第三種方法是用rfind(),其實rfind()和find()差不多,不同之處只是查詢的順序不同。find()從左至右(順序)開始查詢的而rfind()不一樣,它是從右至左(倒序)進行查詢的
import string ss=raw_input('Enter a short sequence:') ls=raw_input('Enter a long sequence:') if(string.rfind(ls,ss)!=-1): print 'find it' else: print 'fail'
下面簡單比較一下find()和rfind()實現字串的查詢
s='kwok'
print s.find('k') #從左到右順序查詢,找到的第一個'k'在第0個索引(即第一個字元)
print s.rfind('k') #從右到左倒序查詢,找到的第一個'k'在第3個索引
(四)第四種方法是index()方法
import string
ss=raw_input('Enter a short sequence:')
ls=raw_input('Enter a long sequence:')
try:
string.index(ls,ss)
print 'find it'
except(ValueError):
print 'fail'
index()方法跟find()方法一樣,只不過如果找不到子字串的話就會報一個ValueError異常
index()方法詳細描述:
Help on function index in module string:
index(s, *args)
index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
(五)第五種方法是rindex()方法,跟rfind()對應,在這裡就不多說了