如何获取元组中的字符数?

时间:2017-05-06 06:17:01

标签: python python-3.x

我在python中有一个元组:

tuple=(“aaa”,”aabc”,”aaara”,”aabsdaaa”)

我想编写一个函数来获取元组中的字符数:

Function((“aaammm”,”aabbcc”,”aaaera”,”aabbaaa”),”a”)
“Character “a” occurred maximum 5 times”

我写了一段代码,但它似乎没有正常工作......你能帮忙吗?

def function(tuple,character):
    count=0
    for ch in tuple:
        if(ch==character):
           count+=1
    return count


print("the",character,"occured:",function(tuple,character),"times")

1 个答案:

答案 0 :(得分:3)

您可以使用str.count来计算字符数,并使用max来获得最大值:

def max_count(strings, substr):
    return max(s.count(substr) for s in strings)

all_strings = ("aaammm", "aabbcc", "aaaera", "aabbaaa")
char = "a"
print("Character \"%s\" occurred maximum %d times" %
      (char, max_count(all_strings, char)))