統計字符串中字母出現的次數,字典形式輸出(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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM