Reputation: 121
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!
Upvotes: 0
Views: 85
Reputation:
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.
Upvotes: 1
Reputation: 3285
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
Upvotes: 1
Reputation: 6181
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)}"
P.s please. avoid using list
as a name of a variable and use, for example, lst
instead since list
is a protected word in Python.
Upvotes: 1