统计一个字符串中相同字符的个数
作为测试小白,苦练代码基本功,啥时候都不嫌晚。
今天在测试群里,看到小伙伴在面试中有个题目,用一段代码对一个字符串进行统计,分别输出字符与数量!!!
于是用业余时间写了下:
#!/usr/bin/env python # -*- coding:utf-8 -*- message = "abcd12311aacc" messagelist = [] def CountOfChar(message): for i in message: list1 = [] for j in message: if i == j: list1.append(i) if list1 not in messagelist: messagelist.append(list1) for i in range(len(messagelist)): print (messagelist[i][0],len(messagelist[i]))
方法二:
#!/usr/bin/env python # -*- coding:utf-8 -*- message = "abcd12311aacc" messagelist = [] def CountOfChar2(message): for msg in message: countmess = message.count(mes) msgstr = msg +":"+ str(countmess) if msgstr not in messagelist: messagelist.append(msgstr) for i in messagelist: print (i) CountOfChar2(message)