""" 输入一段字符串,打印出这个字符串中出现过的字符及出现过的次数 如: 输入:ABCDABCDABA 输出: A : 4 B : 3 C : 2 D : 2 """ char_str = input(‘请输入一个字符串:‘) dirctionary ={} #定义一个空的字典,键为出现的字符,值为该字符出现的次数 for trav in char_str: #将已有的字符都取出来 if trav not in dirctionary: # 如果第一次出现,则将该字符加入到字典的键中,把1作为值 dirctionary[trav] = 1 else: #如果已经存在,则将该字符所在的键的值加1 dirctionary[trav] +=1 for key in dirctionary:#将键遍历出来 print(key,‘:‘,dirctionary[key],‘次‘) #方法二 dirctionary01 = {} for trave in char_str: if trave not in dirctionary01: dirctionary01[trave] =None for trave in dirctionary01: print(trave,‘:‘,char_str.count(trave),‘次‘) #方法三 dirctionary02 = {} for traver in char_str: #if traver not in dirctionary02: dirctionary02[traver] =None for traver in dirctionary02: print(traver,‘:‘,char_str.count(traver),‘次‘)
输入一段字符串,打印出这个字符串中出现过的字符及出现过的次数
原文:https://www.cnblogs.com/touch-prc/p/13040959.html