|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编写一个函数findstr(),该函数统计一个长度为2的子字符串在另一个字符串中出现的次数。例如:假定输入的字符串为"You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.",子字符串为"im",函数执行后打印“子字母串在目标字符串中共出现3次”。
我写的
def findstr():
print("目标", end = "")
temp = input()
print("子目标", end = "")
comp = input()
count = 0
for i in range(len(temp)):
if temp[i] == comp[0] and temp[i+1] == comp[1]:
count = count + 1
if i == len(temp) - 2:
break
print(count)
为什么如果目标是连续的字符串则结果没问题
而目标中出现空格如“ab cdd ef”这样,结果就会出错呢
结果还是正确,如图。另外程序里只判断前2位,所以子目标不管输多少位,都只会判断前2位字符。
顺带优化一下代码:
- def findstr():
- temp = input("目标:")
- comp = input("子目标:")
- count = 0
- for i in range(len(temp)-1):
- if temp[i] == comp[0] and temp[i+1] == comp[1]:
- count = count + 1
- print(count)
复制代码
|
|