程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python judges that the string contains substrings (number, index, all positions)

編輯:Python

Find the substring from left to right, if it exists, output the index value of the first character of the substring, if it does not exist, output -1

# find()a = 'love you'b = 'you'c = 'no'print(a.find(b)) #5print(a.find(c)) #-1

Find the substring from left to right, if it exists, output the index value of the first character of the substring, if it does not exist, output -1

# rfind()a = 'love you'b = 'you'c = 'no'print(a.rfind(b)) #5print(a.rfind(c)) #-1

Count the number of substrings in the parent string

# count()a = 'love you do you love me'b = 'you'c = 'no'print(a.count(b)) #2print(a.count(c)) #0

Find all the positions where the specified string contains substrings and return it as a list

def indexstr(str1,str2):'''Find all positions where the specified string str1 contains the specified substring str2, and return ''' in the form of a listlenth2=len(str2)lenth1=len(str1)indexstr2=[]i=0while str2 in str1[i:]:indextmp = str1.index(str2, i, lenth1)indexstr2.append(indextmp)i = (indextmp + length2)return indexstr2

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved