Home › Learn › Python › Strings in depth

Characters and reversing

Lesson 28 of 40. Walk through a string one character at a time.

A string is a sequence, so everything that works on lists works here: for c in text: visits each character, text[::-1] reverses, len counts, in searches. c.isalpha() asks whether a character is a letter, c.isdigit() a digit, c.lower() lower-cases it.

A palindrome reads the same backwards. The honest version ignores case, spaces, and punctuation: first build a cleaned string of only the lower-case letters, then compare it with its reverse.

text = "Level"
clean = text.lower()
print(clean == clean[::-1])   # True
print(sum(1 for c in text if c in "aeiou"))

Your task

Write is_palindrome(text) that ignores case and every character that is not a letter, and count_vowels(text) that counts a, e, i, o, u in either case.

Hint 1

letters = "".join(c.lower() for c in text if c.isalpha())

Hint 2

count = 0; for c in text.lower(): if c in "aeiou": count += 1

Show the solution
def is_palindrome(text):
    letters = "".join(c.lower() for c in text if c.isalpha())
    return letters == letters[::-1]


def count_vowels(text):
    count = 0
    for c in text.lower():
        if c in "aeiou":
            count += 1
    return count

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.