Lesson · Python for Beginners
Strings and useful text operations
Text is data too, and small string operations can make input easier to use.
What you will learn
- Call common string methods
- Format values with an f-string
- Understand that strings are immutable
Strings are sequences
A string is an ordered sequence of characters. Indexing and slicing can select parts, but an index outside the string's range raises an error. Slices include the start and exclude the stop, matching the convention used by range. Empty text is a valid string with length zero.
Methods return useful results
Methods such as lower, strip, and replace produce a string result. Strings are immutable, so these methods do not change the original string in place. Save the returned value if the cleaned version is the one the rest of the program should use.
Normalize before comparing
People may type extra spaces or different capitalization. Calling strip and lower before comparing can handle those simple differences, while preserving the original input separately may be useful for display. Normalization should match the task: do not remove characters or change case when that would alter a name or other meaningful text.
Format readable messages
An f-string inserts an expression's value inside braces. It is often clearer than joining many pieces with plus signs. Keep formatting at the point where a value is displayed, and keep the original typed value separate from a normalized value when both may be needed.
Split and join with intention
The split method can turn a line into fields, and join can combine strings with a chosen separator. Decide whether repeated spaces or punctuation should be preserved before splitting. Real text may include Unicode characters such as accented letters or emoji, so do not assume that one visible symbol always corresponds to one simple storage unit.
raw_name = ' Mira '
name = raw_name.strip().title()
print(f'Welcome, {name}!')
Expected output
Welcome, Mira!
Practice exercise
Normalize the text ' PYTHON ' by trimming spaces and converting it to lowercase.
Show a hint
Call strip before lower.
Show one possible solution
topic = ' PYTHON '.strip().lower(); print(topic) prints python.
Quick check
Python strings are immutable. Save the returned value to use the stripped text.