+ 2
Can you help me please?
I'm trying to write a code that counts the number of letters in a given string using a function. Here is my code, I keep getting 0. I managed to return just the text, but can't seem to add in the count function. def letter_count(text, letter): a=[text] b=(letter) return(a.count(b)) text = input() letter = input() print(letter_count(text, letter))
14 odpowiedzi
+ 4
JUMP_LINK__&&__Python__&&__JUMP_LINK Learner ,
your statement (count is a string function) could be misunderstood, but there is also a list method count() :
lst = [1,2,1,1]
print(lst.count(1))
# result is: 3
+ 4
Hello!
Try this one, it must work
def letter_count(text, letter):
return text.count(letter)
text = input()
letter = input()
print(letter_count(text, letter))
+ 2
James Murphy ,
your task description is not quite clear. it could mean:
=> count the number of letters in a given string. "hello" result => 5
or
=> count the number of a CERTAIN letter in a given string. "hello", "l" result is => 2
can you please give us a clear and complete task description?
thanks!
+ 2
Just removing the [ ] and () worked so thanks very much Python Learner
+ 1
James Murphy Change it to 'text.count(letter)' and it should work without any problems.
+ 1
Hi James!
That's because count() is a string function. But you're applying this to a list and a tuple. Hope you know "[]" is used to denote list and "()" is for tuple in Python. Inorder to solve this issue, you can remove the square brackets and parentheses from the assigned variables.
+ 1
Thanks all,
Lothar, sorry I wasn't clear. I need to count the number of times a specific letter appears in the string. Both the text and letter to be counted come from input()
+ 1
I think that this ⬆️ is what I was trying to do.
0
James Murphy How about this one? :-
def foo(text, letter):
return text.count(letter)
print(foo(input(), input()))
# I hope that this helps. Happy coding!
0
[This comment will be deleted soon]
Recently, I've been receiving downvotes without any explanation. In my opinion, this is really bad without a proper justification.
0
# Not mine
# credit: https://www.sololearn.com/Discuss/2896020/JUMP_LINK__&&__python__&&__JUMP_LINK-how-many-letters
def letter_count(text, letter):
#your code goes here
return text.count(letter)
text = str(input())
letter = str(input())
print(letter_count(text,letter))
0
def letter_count(text, letter):
i =0
for x in text:
if x == letter:
i=i+1
return i
text = input()
letter = input()
print(letter_count(text, letter))
I hope it works
- 1
I will try out these suggests, thanks very much.
I knew the [ ] would create a list, I thought that I needed to put the string into a list to be able to do the count.
- 1
Here is the original problem:
Write a function that takes a string and a letter as its arguments and returns the count of the letter in the string.
Sample Input
hello, how are you?
o
Sample Output
3
Explanation
The letter o appears 3 times in the given text.