Back to Freecodecamp

Challenge 200: Letter and Number Count

curriculum/challenges/english/blocks/daily-coding-challenges-python/698a1a73ade5ac0e19180fa3.md

latest2.4 KB
Original Source

--description--

Given a string, return a message with the count of how many letters and numbers it contains.

  • Letters are A-Z and a-z.
  • Numbers are 0-9.
  • Ignore all other characters.

Return "The string has X letters and Y numbers.", where "X" is the count of letters and "Y" is the count of numbers. If either count is 1, use the singular form for that item. E.g: "1 letter" instead of "1 letters" and "1 number" instead of "1 numbers".

--hints--

count_letters_and_numbers("helloworld123") should return "The string has 10 letters and 3 numbers.".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(count_letters_and_numbers("helloworld123"), "The string has 10 letters and 3 numbers.")`)
}})

count_letters_and_numbers("Catch 22") should return "The string has 5 letters and 2 numbers.".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(count_letters_and_numbers("Catch 22"), "The string has 5 letters and 2 numbers.")`)
}})

count_letters_and_numbers("A1!") should return "The string has 1 letter and 1 number.".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(count_letters_and_numbers("A1!"), "The string has 1 letter and 1 number.")`)
}})

count_letters_and_numbers("12345") should return "The string has 0 letters and 5 numbers.".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(count_letters_and_numbers("12345"), "The string has 0 letters and 5 numbers.")`)
}})

count_letters_and_numbers("password") should return "The string has 8 letters and 0 numbers.".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(count_letters_and_numbers("password"), "The string has 8 letters and 0 numbers.")`)
}})

--seed--

--seed-contents--

py
def count_letters_and_numbers(s):

    return s

--solutions--

py
def count_letters_and_numbers(s):
    letter_count = 0
    number_count = 0

    for char in s:
        if ('A' <= char <= 'Z') or ('a' <= char <= 'z'):
            letter_count += 1
        elif '0' <= char <= '9':
            number_count += 1

    letter_word = "letter" if letter_count == 1 else "letters"
    number_word = "number" if number_count == 1 else "numbers"

    return f"The string has {letter_count} {letter_word} and {number_count} {number_word}."