I got stuck on a homework problem where I need to write a function that takes in one parameter and returns True if there are exactly three 7's in a string. If there are less than three or more than three '7's, the function should return False.
def lucky_seven(a_string):
if "7" in a_string:
return True
else:
return False
print(lucky_seven("happy777bday"))
print(lucky_seven("happy77bday"))
print(lucky_seven("h7app7ybd7ay"))
The result should be True, False, True. I got I to work where only one 7 is in a string. Appreciate if anyone can point me into the right direction.
you can use str.count:
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
def lucky_seven(a_string):
if a_string.count("7") == 3:
return True
else:
return False
print(lucky_seven("happy777bday"))
print(lucky_seven("happy77bday"))
print(lucky_seven("h7app7ybd7ay"))
You an do it by using regexp easily:-
import re
def lucky_seven(text):
return len(re.findall("7", text)) is 3
print(lucky_seven("happy777bday"))
print(lucky_seven("happy77bday"))
print(lucky_seven("h7app7ybd7ay"))
"7" in a_string
is True iff there are any 7
's in a_string
; to check for a certain number of 7
s, you could compare each character of a_string
to 7
and count how many times they match. You could also do this with a regex.
You could just create your own counter like -
def lucky_seven(a_string):
count = 0
for s in a_string:
if s == "7":
count += 1
return True if count == 3 else False
Or you could use python's collections
module, which will return a dict of how many times an element has appeared in a list. Since a string is nothing but a list, it will work -
import collections
def lucky_seven(a_string):
return True if collections.Counter("happy777bday")["7"] == 3 else False
Or a string counter-
def lucky_seven(a_string):
return True if str.count(a_string, "7") == 3 else False
Or even a list comprehension solution, though really not needed -
def lucky_seven(a_string):
return True if len([i for i in a_string if i == "7"]) == 3 else False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.