Case and Cleanup Methods

Case and Cleanup Methods

Strings have methods, called with a dot like list methods. Because strings cannot be changed in place, every string method returns a new string and leaves the original alone.

upper and lower change case:

name = "Ada"
print(name.upper())
print(name.lower())
print(name)

Output:

ADA
ada
Ada

The last line shows the original unchanged. To keep a method's result, assign it: name = name.upper().

strip removes whitespace from both ends — common when cleaning up user input:

answer = "  yes \n"
print(answer.strip())

Output:

yes

replace swaps every occurrence of one substring for another:

print("2026-07-15".replace("-", "/"))

Output:

2026/07/15

Exercise

  1. Define a function named normalize with one parameter, text.
  2. It returns text with surrounding whitespace removed and all letters lowercased.

normalize(" YES ") returns "yes".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestNormalize(unittest.TestCase):
    def test_strips_and_lowercases(self):
        self.assertEqual(normalize("  YES "), "yes")

    def test_already_clean_text_is_unchanged(self):
        self.assertEqual(normalize("no"), "no")

    def test_mixed_case_with_newline(self):
        self.assertEqual(normalize("Maybe\n"), "maybe")

    def test_inner_spaces_are_kept(self):
        self.assertEqual(normalize(" New York "), "new york")
def normalize(text):
    return text.strip().lower()


print(normalize("  YES "))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.