简体   繁体   中英

count letter in words using Python

I am working with Python to write a function Here is an example: lettercount(['hello','it','is','me'],'i') should return ['it-1','is-1'] .

Here is my code:

def lettercount(list, letter):
    result = []           #create an empty list
    for word in list:            #traverse through all the words in the provided list
        if word not in result:        #from this line I don't know what I'm really doing though
            if letter in word:                
                wrd = "{}-".format(word).append(word.count(letter))     
 #tried to achieve the same format as provided but failed
                result.append(wrd)               #this is wrong because str doesn't have the attribute "append"
    return result        

Can someone give me a hint on this problem? Thanks so much!

The problem is the way you construct wrd . Change this line -

wrd = "{}-".format(word).append(word.count(letter))     

To -

wrd = f"{word}-{word.count(letter)}"

Ps please. avoid using list as a name of a variable and use, for example, lst instead since list is a protected word in Python.

def lettercount(lst, letter): out = [] for word in lst: cnt = sum(1 for l in word if l == letter) if cnt: out.append(f'{word}-{cnt}') return out

Try:

def lettercount(lst, letter):
    result = []
    for word in lst:
        if letter in word:
            result.append(word + '-' + str(word.count(letter)))

And I don't recommend naming variables "list" because it's an existing keyword in Python.

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