034. String Methods
Built-in operations on text values
034. String Methods
RAM Manager: Parsing Process Names
Aryan’s tool reads process names from /proc/PID/cmdline — they come back with leading/trailing whitespace, inconsistent casing, and full paths like /usr/bin/python3. He needs to normalize them before display.
# Raw data from the OS
raw_cmd = " /usr/bin/Python3 "
# What Aryan wants in the UI
"Python3" # stripped, just the basename
"python3" # lowercased for comparisonHe’s writing normalize_process_name(cmd) and a word counter for log lines. The broken code has three separate bugs — each function is wrong in a different way.
💡 Fun fact: Python strings are immutable — every method like .lower() or .strip() returns a brand-new string object rather than modifying the original. This design choice is why Python strings can safely be used as dictionary keys and why two variables can share the same string object without risk.
⚠️ Watch out: Beginners often chain .strip().lower() in the wrong order or forget to chain at all. email.lower() on " [email protected] " returns " [email protected] " — the spaces are still there! Always .strip() before case conversion to avoid hiding whitespace bugs.
🤔 Think about it: If "hello".upper() returns "HELLO" and "HELLO".lower() returns "hello", what do you think "Hello World".swapcase() returns — and when in real systems would that ever be useful?
Learning objectives
- Use strip(), lower(), upper(), title() for text normalization
- Use split() to break text into words
- Use isdigit(), isalpha() for character classification
Key concepts
- string methods
- strip()
- lower()
- title()
- split()
Try it
Concept detail
Python strings are immutable — every method returns a NEW string, never modifies in place.
Case conversion: lower() → all lowercase upper() → ALL UPPERCASE title() → Each Word Capitalized capitalize() → First letter only swapcase() → sWAP cASE
Whitespace: strip() → remove leading and trailing whitespace (spaces, tabs, newlines) lstrip() → left side only rstrip() → right side only strip(“x”) → remove specific character instead of whitespace
Testing characters: isdigit() → True if ALL chars are digits isalpha() → True if ALL chars are letters isalnum() → True if ALL chars are letters or digits isspace() → True if ALL chars are whitespace
Word operations: split() → split on any whitespace, drops empty strings split(“,”) → split on specific delimiter count(“x”) → count non-overlapping occurrences of “x” find(“x”) → index of first occurrence, -1 if not found replace(a,b) → replace all occurrences of a with b
Solution
def normalize_email(email):
return email.strip().lower()
def title_case_name(name):
return name.title()
def count_words(text):
return len(text.split())
def has_digits(text):
for char in text:
if char.isdigit():
return True
return FalseTests
def test_email_strips_and_lowercases():
assert normalize_email(" [email protected] ") == "[email protected]"
def test_email_no_whitespace_still_works():
assert normalize_email("[email protected]") == "[email protected]"
def test_title_case():
assert title_case_name("john doe smith") == "John Doe Smith"
def test_title_case_not_upper():
result = title_case_name("hello world")
assert result != "HELLO WORLD", "upper() was used instead of title()"
assert result == "Hello World"
def test_count_words():
assert count_words("hello world") == 2
assert count_words(" one two three ") == 3
assert count_words("") == 0
def test_count_words_not_characters():
assert count_words("hello") == 1, "len(text) counts characters, not words"
def test_has_digits_true():
assert has_digits("abc123") == True
def test_has_digits_false():
assert has_digits("abcdef") == False