简体   繁体   中英

Ignore Whitespace while counting number of characters in a String

I am trying to write a function which will count the number of characters present in an input string and store as key-value in a dictionary.The code is partially working ie it is also counting the whitespaces present in between 2 words.How do I avoid counting the whitespaces?

#Store Characters of a string in a Dictionary

    def char_dict(string):
        char_dic = {}
        for i in string:
            if i in char_dic:
                char_dic[i]+= 1
            else:
                char_dic[i]= 1
        return char_dic
    
    print(char_dict('My name is Rajib'))

You could just continue if the character is a white space:

def char_dict(string):
    char_dic = {}
    for i in string:
        if ' ' == i:
            continue
        if i in char_dic:
            char_dic[i] += 1
        else:
            char_dic[i]= 1
    return char_dic

print(char_dict('My name is Rajib')) # {'j': 1, 'm': 1, 'M': 1, 'i': 2, 'b': 1, 'e': 1, 'a': 2, 'y': 1, 'R': 1, 'n': 1, 's': 1}

A cleaner solution would be:

from collections import defaultdict

def countNonSpaceChars(string):
    charDic = defaultdict(lambda: 0)
    for char in string:
        if char.isspace():
            continue
        charDic[char] += 1
    return dict(charDic)

print(countNonSpaceChars('My name is Rajib')) # {'i': 2, 'a': 2, 'R': 1, 'y': 1, 'M': 1, 'm': 1, 'e': 1, 'n': 1, 'j': 1, 's': 1, 'b': 1}

You can delete space -> string = string.replace (" ","")

def char_dict(string):
    char_dic = {}
    string=string.replace(" ","")
    for i in string:
        if i in char_dic:
            char_dic[i]+= 1
        else:
            char_dic[i]= 1
    return char_dic

print(char_dict('My name is Rajib'))

To simplify things for you, there's a library called collections that has a Counter function that will produce a dictionary of values and their occurrences in a string. Then, I would simply remove the whitespace key from the dictionary if it is present using the del keyword.

from collections import Counter

def char_dict(string):
    text = 'My name is Rajib'
    c = Counter(text)
    if ' ' in c: del c[' ']

print(char_dict('My name is Rajib'))

This method is very readable and doesn't require too much reinventing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM