python学习笔记:子字符串索引、查找、计数

一、索引特定位置字符

    即引用字符串s中特定位置字符。从0开始,如果为负数X等价于len(s)-X

s="abcdefg"
print(s[0])           #a
print(s[1])           #b
print(s[2])           #c
print("------")       
print(s[len(s)-1])    #g
print(s[len(s)])      #error
print(s[-1])          #==s[len(s)-1]    g

二、判断符串中是否存在某个字符串 

print("ring" in "strings")     #True
print("wow" in "amazing!")     #False
print("Yes" in "yes!")         #False
print("" in "No way!")         #True

三、字符串特定子字符串/字符计数

s.count(sub, start=num1,end=num2):统计字符串中子字符串sub出现的次数,start(起始位置)、end(结束位置)可缺省

四、查找字符串中子字符串的位置

(1)S.find(sub):检查字符串S是否有子字符串sub,返回子字符串sub的起始位置。若sub不在S中,返回-1

(2)S.index(sub):返回字符串S中子字符串sub的起始位置。若sub不在S中,引发“valueerror”

print("This is a history test".count("is")) # 3
print("This IS a history test".count("is")) # 2
print("-------")
print("Dogs and cats!".find("and"))         # 5
print("Dogs and cats!".find("or"))          # -1
print("-------")
print("Dogs and cats!".index("and"))        # 5
print("Dogs and cats!".index("or"))         # crash!

猜你喜欢

转载自blog.csdn.net/xiaozhimonica/article/details/85047812