统计字符串中字母出现的次数,字典形式输出(python)

a = "aAsmr3idd4bgs7Dlsf9eAF"

请将a字符串的数字取出,并输出成一个新的字符串。

请统计a字符串出现的每个字母的出现次数(忽略大小写,a与A是同一个字母),并输出成一个字典。 例 {'a':3,'b':1}

请去除a字符串多次出现的字母,仅留最先出现的一个,大小写不敏感。例 'aAsmr3idd4bgs7Dlsf9eAF',经过去除后,输出 'asmr3id4bg7lf9e'

a = "aAsmr3idd4bgs7Dlsf9eAF"

def fun1_2(x): #1&2

    x = x.lower() #大小写转换

    num = []

    dic = {}

    for i in x:

        if i.isdigit():  #判断如果为数字,请将a字符串的数字取出,并输出一个新的字符串

            num.append(i)

        else:   #2 请统计a字符串出现每个字母的出现次数(忽视大小写),并输出一个字典。例:{'a':3,'b':1}

            if i in dic:

                        continue

            else:

                dic[i] = x.count(i)  

    new = ''.join(num)

    print "the new numbers string is: " + new

    print "the dictionary is: %s" % dic

fun1_2(a)

 

def fun3(x):

    x = x.lower()

    new3 = []

    for i in x:

        if i in new3:

                continue

        else:

            new3.append(i)

    print ''.join(new3)

fun3(a)

Console:

the new numbers string is: 3479

the dictionary is: {'a': 3, 'b': 1, 'e': 1, 'd': 3, 'g': 1, 'f': 2, 'i': 1, 'm': 1, 'l': 1, 's': 3, 'r': 1}

asmr3id4bg7lf9e

原文地址:https://www.cnblogs.com/sunshishi/p/4773096.html