String Methods and Formatting
Unit ID: M02-U05 Estimated active time: 22-30 minutes
Clean text in visible steps
Real text often contains inconsistent spaces or letter case.
raw_status = " PLANNED "
clean_status = raw_status.strip().lower()
print(clean_status)
Output:
planned
strip() removes whitespace at the beginning and end. lower() creates a lowercase version. The original string remains unchanged.
Other useful methods include:
text = "python foundations"
print(text.upper())
print(text.title())
print(text.replace("foundations", "practice"))
print(text.startswith("python"))
print(text.endswith("practice"))
Methods are called with dot notation: the object, a dot, and the method name.
Chaining methods
This code applies two operations in sequence:
clean_name = " python foundations ".strip().title()
print(clean_name)
Output:
Python Foundations
Use short chains when each step remains clear. For a complex cleaning rule, use separate named steps so you can inspect the intermediate values.
Format output with f-strings
An f-string places values inside readable text:
course_name = "Python Foundations for AI"
course_hours = 32
print(f"{course_name} has {course_hours} course hours.")
Output:
Python Foundations for AI has 32 course hours.
The leading f tells Python to evaluate expressions inside braces.
Format numbers for display
average_hours = 32 / 9
print(f"Average hours per module: {average_hours:.2f}")
The display shows two digits after the decimal point. The underlying value in average_hours has not been changed.
Display formatting and calculation rules are different. Do not use formatted text as though it were still a number.
Quotes inside strings
Use one quotation style around text containing the other:
message = "Python's rules are learnable."
quote = 'The learner said, "I can trace this."'
You can also escape a matching quote with a backslash, but choose the clearest readable form.
Practice
Start with:
raw_course = " PYTHON foundations FOR ai "
course_hours = 32
Create a cleaned lowercase version, then create a display version using .title(). Notice that .title() produces Ai, not the abbreviation AI. Correct the display value with .replace("Ai", "AI").
Print:
Course: Python Foundations For AI | Course hours: 32
Then explain why the cleaning value and display value may be kept separately.
Takeaway
String methods create cleaned or transformed text. F-strings combine values into readable output without unsafe text-number concatenation. Inspect intermediate values when a cleaning rule has several steps. Next, we will distinguish missing information from zero and empty text.
