2024-06-12 08:55:44 发布
网友
查找第二个参数是否在第一个参数中连续出现3次的简单脚本。我能找到第二个论点是否在第一个论点中,有多少次,等等,但我怎么看它是否连续出现了3次
#!/usr/bin/python import string def three_consec(s1,s2) : for i in s1 : total = s1.count(s2) if total > 2: return "True" print three_consec("ABABA","A")
total = s1.count(s2)将为您提供s1中的s2出现次数,而不管您的位置i
total = s1.count(s2)
s1
s2
i
相反,只需遍历字符串,并在看到字符时继续计数s2:
def three_consec (string, character): found = 0 for c in string: if c == character: found += 1 else: found = 0 if found > 2: return True return False
或者,您也可以采用另一种方式,只需查看字符串中是否出现“字符的三倍”:
def three_consec (string, character): return (character * 3) in string
它使用的功能是,可以将字符串乘以一个数字来重复该字符串(例如,'A' * 3将为您提供'AAA'),并且in运算符可用于检查字符串中是否存在子字符串
'A' * 3
'AAA'
in
total = s1.count(s2)
将为您提供s1
中的s2
出现次数,而不管您的位置i
相反,只需遍历字符串,并在看到字符时继续计数
s2
:或者,您也可以采用另一种方式,只需查看字符串中是否出现“字符的三倍”:
它使用的功能是,可以将字符串乘以一个数字来重复该字符串(例如,
'A' * 3
将为您提供'AAA'
),并且in
运算符可用于检查字符串中是否存在子字符串相关问题 更多 >
编程相关推荐