user1294377
user1294377

Reputation: 1081

How would I go about counting the number of consonants in a word? python

In python, how would I go about counting the number of consonants in a word? I realize there are a couple different ways to do this, but I think my way of choice would be to analyze each letter of a word and add to a counter when I encounter a consonant. I just can't figure out how to implement it.

Something starting with this?

count = 0
consonant = 'astringofconsonants'
if consonant in string[0]:
    count += 1

Upvotes: 1

Views: 1798

Answers (4)

jamylak
jamylak

Reputation: 133624

The start you have given is not very pythonic.

Try iterating through the list using

for c in word:
    if c in consonants:
        # do something

You could also use a generator like the following. It will go through each letter and count the number of each consonant is in the word.

(word.count(c) for c in consonants)

use the sum() function to add them all up

Upvotes: 0

Blender
Blender

Reputation: 298364

You can iterate over strings the same way you iterate over a list:

for letter in word:
  if letter in consonants:
    # You can fill in from here

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799082

Iterating over a string yields each character in turn.

for c in 'thequickbrownfoxjumpsoverthelazydog':
    print c

Upvotes: 1

Interrobang
Interrobang

Reputation: 17434

Comprehensions!

count = sum(1 for c in cons if c not in ['a','e','i','o','u'])

From comments, probably more Pythonic:

count = len([c for c in cons if c not in 'aeiou'])

Upvotes: 1

Related Questions