1

How do I apply a for loop to a string in Python which allows me to count each letter in a word? The ultimate goal is to discover the most common letter.

This is the code so far:

 print "Type 'exit' at any time to exit the program."

 continue_running = True
 while continue_running:


word = raw_input("Please enter a word: ")
if word == "exit":
    continue_running = False

else:
    while not word.isalpha():
        word = raw_input("ERROR: Please type a single word containing alphabetic characters only:")
    print word

    if len(word) == 1:
        print word + " has " + str(len(word)) + " letter."
    else:
        print word + " has " + str(len(word)) + " letters."

    if sum(1 for v in word.upper() if v in ["A", "E", "I", "O", "U"]) == 1:
        print "It also has ", sum(1 for v in word.upper() if v in ["A", "E", "I", "O", "U"]), " vowel."
    else:
        print "It also has ", sum(1 for v in word.upper() if v in ["A", "E", "I", "O", "U"]), " vowels."

    if sum(1 for c in word if c.isupper()) == 1:
        print "It has ", sum(1 for c in word if c.isupper()), " capital letter."
    else:
        print "It has ", sum(1 for c in word if c.isupper()), " capital letters."

    for loop in word:

I know I can use the:

(collections.Counter(word.upper()).most_common(1)[0])

format, but this isn't the way I want to do it.

1
  • Example added, last line of code is the only problem. Commented Mar 10, 2015 at 12:03

2 Answers 2

3

You can simply loop directly over strings; they are sequences just like lists and tuples; each character in the string is a separate element:

for character in word.upper():
    # count the character.

Counts can then be collected in a dictionary:

counts = {}
for character in word.upper():
    # count the character.
    counts[character] = counts.get(character, 0) + 1

after which you'd pick the most common one; you can use the max() function for that:

most_common = max(counts, key=counts.__getitem__)  # maximum by value

Demo:

>>> word = 'fooBARbazaar'
>>> counts = {}
>>> for character in word.upper():
...     # count the character.
...     counts[character] = counts.get(character, 0) + 1
... 
>>> counts
{'A': 4, 'B': 2, 'F': 1, 'O': 2, 'R': 2, 'Z': 1}
>>> max(counts, key=counts.__getitem__)
'A'
Sign up to request clarification or add additional context in comments.

21 Comments

How could I use this to help me count characters from word?
Sorry, I'm fairly new to this. I have written the first two pieces of code you wrote and ran the module, and nothing has happened.
@poddpython: did you try to print anything? Something probably happened, but if you don't produce output to show anything you won't notice.
word.upper() is the correct thing, I'm just struggling to get this to work. Sorry
I just got something, I'll edit the question for you to see. :)
|
0

If you don't want to re-invent the wheel try using Counter

>>> from collections import Counter
>>> x = Counter("stackoverflow")
>>> x
Counter({'o': 2, 'a': 1, 'c': 1, 'e': 1, 'f': 1, 'k': 1, 'l': 1, 's': 1, 'r': 1, 't': 1, 'w': 1, 'v': 1})
>>> print max(x, key=x.__getitem__)
o
>>> 

1 Comment

The OP managed to remove that again from their question, but they explicitly stated they did not want to use a Counter(). Also, why are you ignoring the Counter.most_common() method to get the most common character?

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.