0

I am wondering how to count specific letters in a string. The first thing that popped into my head was the function len. Out of curiosity, is there a way to write this code without using built in functions and using len?

There is a question asked similar to this here and I am having trouble understanding it.

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count = count + 1
  return count

What exactly is going on in if char == c: and count += 1? I understand why the person started with a for loop but I don't understand why place an if after?

1
  • 1
    char is the letter you want to count how many times it appears in word. You iterate on the letters of word and if it's the letter you want, you add the counter by 1. Commented Jul 28, 2014 at 6:59

6 Answers 6

2

The if is needed because you only want to count instances of a specific character, char. Without it, you would wind up doing count = count + 1 for every character in the string, so you'd get the full string length, not the amount of specific character you're looking for.

With comments in code:

for c in word:            # go through each character in code
    if char == c:         # if the character is the one we're counting
        count = count + 1 # add one to the current count of characters
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I understand why the if is needed now. The count +=1 is needed because the loop needs to be iterated, correct?
@Robben, no, for does that automatically - the count variable keeps track of how many of the letters you're looking for you've found. count += 1 simply adds one to the count whenever you find the right char.
Thanks, you've been of great help!
2

Strings have a built in count() method:

>>> s = 'aaabbbccc'
>>> s.count('a')
3
>>> s.count('aa')
1

Comments

0

Have you tried the Python Wiki?

It states that ANY object with an iterating function can be cycled through, which answers your second question.

Since you don't want to use the len function, you can use the for loop like in the answer you linked to cycle through the object (the String word) looking for the character char, recording each time the char is found with count.

The parameter char needs to be found in word parameter, and so c is just a variable to set to each letter (or character, not all parts of the String may be an alphabetical letter) as it cycles through word.

The reason for the if statement is so when the cycling variable c equals char, the block can be executed. In this particular block, the count is being iterated up (count = count + 1), and once the function is done with iterating through the for loop, it will return count (how many times char was found, effectively counting specific letters in the String as you asked for).

Long-winded but in short, yes, that function you posted will give you a count of how many times the letter is in the word.

Comments

0

You want to count only for specific char. Meaning that if you have the word "hello" and the letter "l", you want to return 2 because "l" appears 2 times in "hello".

The if simply checks if the char is the char you want, if that's the case, you increment the counter by one - for c in word: iterates on the chars of word.

Python's syntax is very readable and easy to understand, try to speak the code and you'll understand what it does.

Another way to do that is:

print len([c for c in word if c == char])

Example:

[c for c in 'hello world' if c == 'l']

Will return:

['l', 'l', 'l']

Then len will return 3.

2 Comments

Thank you! For print len([c for c in word if c == char]) I see that c += 1 is not needed there, why is that? What exactly does c += 1 do?
@Robben It's c = c + 1 (The latter is not supported in Python). c += 1 is not needed because I create a list contains the letters, then I use len on it. Try to print each part to better understand what's going on. See my edit.
0

Using collections.Counter

>>> word = "Hallelujahhhhh"
>>> from collections import Counter
>>> Counter(word)
Counter({'h': 5, 'l': 3, 'a': 2, 'e': 1, 'H': 1, 'j': 1, 'u': 1})

Comments

0
for c in word:

In this statement word will be taken as a list of a string, c is each character from that list. That means loop will repeat for each character of the word.

So in this statement if char == c: for every character of word will be compare with char.

If the statement is true then count will increase by 1.

So, As per your question

if char == c: compare char with each character of word

and

count+=1 will increase the value of count by 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.