我的老师让我写一个函数,通过使用另一个字母来计算字符串的出现次数。例如:
>>>problem3("all is quiet on the western front", "tqe")
>>>["t=4", "q=1", "e=4"]
然而我只能这样做:
>>>problem3("all is quiet on the western front", "tqe")
>>>[4, 1, 4]
这是我的代码:
def problem3(myString, charString):
return [myString.count(x) for x in (charString)]
我如何以这种格式获得[" t = 4"," q = 1"," e = 4"]?
答案 0 :(得分:1)
所以你被要求非常具体地格式化它并且你很接近,只需要格式化结果:
def problem3(myString, charString):
return ['{}={}'.format(x, myString.count(x)) for x in charString]
>>> problem3("all is quiet on the western front", "tqe")
['t=4', 'q=1', 'e=4']