Is there any way i can loop through a-z instead of writing multiple for loop stataments?

Viewed 109

So im trying to do a charachter count on a given list.

a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]

my expected output is:

farshad contains 2 a

And this goes on .....

My code is:

def charCount():
    a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]

    for word in a:
        for letter in word:
            x = word.count("a")
        print(word, "contains", x, "a")

    for word in a:
        for letter in word:
            x = word.count("d")
        print(word, "contains", x, "d")

charCount()

Im trying to do this all in one for loop, for example A-Z ....

Thanks for your help :D

3 Answers

You can do this in 2 for loops. (I assume the question means 1 separate for loops and allows nested for loops) This is how I did it:

import string

def charCount():
    a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]

    for word in a:
        for i in string.ascii_lowercase:
            x = word.lower().count(i)
            print(word, "contains", x, i)

charCount()

All you need to do is loop through every character. string.ascii_lowercase contains every single lowercase letter, so I used that. Then, we get the count of i in word.lower(). word.lower() turns the word into lowercase making it count for capitals as well.

If you wanted to shorten it further, you could change the inner for loop like this:

def charCount():
    a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]

    for word in a:
        for i in string.ascii_lowercase: print(word, "contains", word.lower().count(i), i)

Are you wanting to go through the whole alphabet for each word? Or just the letters in those words?

If you're only wanting to count the letters in each word you can try:

def charCount():

    a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]

    for word in a:

        word_set = set(word)

        for letter in word_set:
            x = word.count(letter)
            print(word, "contains", x, letter)

This will create a set for each word, which will prevent duplicate letters from being printed.

If you're wanting to ignore those question marks, you could put this inside the inner loop:

            if letter == '?':
                continue

Bear in mind this solution won't order your letters in any particular order as sets are inherently unordered.

my answer

def charCount(search_letter):
    a = ["farshad", "ghassemi?d", "madam", "?radar?", "duration", "con?tained"]
    for word in a:
        word = word.lower()
        for letter in word:
            x = word.count(search_letter)
            print(word, "contains", x, search_letter)
# letters = ("aeiou")
letters = ("abcdefghijklmnopqrstuvwxyz")    
for search_letter in letters:
    charCount(search_letter)
Related