如有字符串mystr = ‘hello world itcast and itcastcpp‘
,以下是常见的操作
检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1
mystr.find(str, start=0, end=len(mystr))
# 定义一个字符串 a = "eabcabdef" # <1>find # 查看一个字符或者字符串子串在字符串中的位置(下标索引) # 返回的都是从左到右的下标索引 # 找到返回下标索引 # 找不到返回-1 ret = a.find("abc") print(ret)
运行结果:1
# 定义一个字符串 a = "eabcabdef" # <1>find # 查看一个字符或者字符串子串在字符串中的位置(下标索引) # 返回的都是从左到右的下标索引 # 找到返回下标索引 # 找不到返回-1 index = a.find("qq") print(index)
运行结果:-1
跟find()方法一样,只不过如果str不在 mystr中会报一个异常.
mystr.index(str, start=0, end=len(mystr))
# 定义一个字符串 a = "eabcabdef" # <2>index # 找到返回下标索引 # 找不到就会报错 ret = a.index("qq") print(ret)
运行结果:报错
ValueError: substring not found
返回 str在start和end之间 在 mystr里面出现的次数
mystr.count(str, start=0, end=len(mystr))
# 定义一个字符串 a = "eabcabdef" # <3>count ret = a.count("ab1") print(ret)
运行结果;0
把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.
mystr.replace(str1, str2, mystr.count(str1))
# 定义一个字符串 a = "eabcabdef" # <4>replace ret1 = a.replace("a", "X", 1) # # 字符串是不可变的数据类型 # print(a) print(ret1)
运行结果:
eXbcabdef
以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
mystr.split(str=" ", 2)
例子:
# 定义一个字符串 a = "eabcabdef" # <5>split # str -> list(了解) ret2 = a.split("a", 1) print(ret2)
运行结果:
[‘e‘, ‘bcabdef‘]
原文:https://www.cnblogs.com/kangwenju/p/12731142.html