Letter Count on a string
Python newb here. I m trying to count the number of letter "a"s in a given string. Code is below. It keeps returning 1 开发者_开发技巧instead 3 in string "banana". Any input appreciated.
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
count += 1
return count
print count_letters('banana','a')
The other answers show what's wrong with your code. But there's also a built-in way to do this, if you weren't just doing this for an exercise:
>>> 'banana'.count('a')
3
Danben gave this corrected version:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
Here are some other ways to do it, hopefully they will teach you more about Python!
Similar, but shorter for
loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:
def count_letters(word, char):
count = 0
for c in word:
count += (char == c)
return count
Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn't match char
and 1 if it does, and then sums them:
def count_letters(word, char):
return sum(char == c for c in word)
The next one filters out all the characters that don't match char
, and counts how many are left:
def count_letters(word, char):
return len([c for c in word if c == char])
One problem is that you are using count
to refer both to the position in the word that you are checking, and the number of char
you have seen, and you are using char
to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.
Also, move the return
statement outside the loop; otherwise you will always return after checking the first character.
Finally, you only need one loop to iterate over the string. Get rid of the outer while
loop and you will not need to track the position in the string.
Taking these suggestions, your code would look like this:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
A simple way is as follows:
def count_letters(word, char):
return word.count(char)
Or, there's another way count each element directly:
from collections import Counter
Counter('banana')
Of course, you can specify one element, e.g.
Counter('banana')['a']
Your return
is in your for loop! Be careful with indentation, you want the line return count
to be outside the loop. Because the for loop goes through all characters in word
, the outer while loop is completely unneeded.
A cleaned-up version:
def count_letters(word, to_find):
count = 0
for char in word:
if char == to_find:
count += 1
return count
You have a number of problems:
- There's a problem with your indentation as others already pointed out.
- There's no need to have nested loops. Just one loop is enough.
- You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.
This code fixes all these errors:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
A much more concise way to write this is to use a generator expression:
def count_letters(word, char):
return sum(char == c for c in word)
Or just use the built-in method count that does this for you:
print 'abcbac'.count('c')
I see a few things wrong.
- You reuse the identifier
char
, so that will cause issues. - You're saying
if char == word[count]
instead ofword[some index]
- You return after the first iteration of the for loop!
You don't even need the while
. If you rename the char param to search
,
for char in word:
if char == search:
count += 1
return count
Alternatively You can use:
mystring = 'banana'
number = mystring.count('a')
count_letters=""
number=count_letters.count("")
print number
"banana".count("ana")
returns 1 instead of 2 !
I think the method iterates over the string (or the list) with a step equal to the length of the substring so it doesn't see this kind of stuff.
So if you want a "full count" you have to implement your own counter with the correct loop of step 1
Correct me if I'm wrong...
def count_letter(word, char):
count = 0
for char in word:
if char == word:
count += 1
return count #Your return is inside your for loop
r = count_word("banana", "a")
print r
3
x=str(input("insert string"))
c=0
for i in x:
if 'a' in i:
c=c+1
print(c)
Following program takes a string as input and output a pandas DataFrame, which represents the letter count.
Sample Input
hello
Sample Output
char Freq.
0 h 1
1 e 1
2 l 2
3 o 1
import pandas as pd
def count_letters(word, char):
return word.count(char)
text = input()
text_split = text.split()
list1 = []
list2 = []
for i in text_split:
for j in i:
counter = count_letters (text, j)
list1.append(j)
list2.append(counter)
dictn = dict(zip(list1, list2))
df = pd.DataFrame (dictn.items(), columns = ['char', 'freq.'])
print (df)
精彩评论