Working with text and files
Useful string methods
Clean and inspect text with strip(), lower(), split(), and join().
Lesson 29 of 63
Reading: about 2 min
Lesson + practice: about 11 min
Difficulty: Beginner
On this page4 sections
Strings have methods for common text tasks. strip() removes whitespace at both ends, lower() returns lowercase text, and split() separates text into a list. These methods return new values; they do not change the original string.
raw = " Python, SQL, Excel "
clean = raw.strip()
topics = clean.split(", ")
print(clean)
print(topics)
print(raw)Python, SQL, Excel ['Python', 'SQL', 'Excel'] Python, SQL, Excel
Join and normalise
join() combines a sequence of strings using a separator. lower() can make case-insensitive comparisons when both sides are converted.
topics = ["Python", "SQL"]
print(" | ".join(topics))
print("PYTHON".lower() == "python")Python | SQL True
Why this works
A string method returns a result based on the original text. strip() removes whitespace only at the ends, so spaces within "Python, SQL" remain. split(", ") uses that exact separator, and join() performs the opposite kind of operation by combining separate strings.
Practice
Start with " loops, files ". Remove outer spaces, split it into two topics, and join the topics with " / ".
Does raw.strip() change raw itself?
Reveal answer
No. It returns a new string; assign that result if you want to keep it.
Try another case
What does " A, B ".strip().split(", ") produce?
Check your answer
Reveal answer
It produces ["A", "B"].
Your progress
Reveal the check answer or reach the end to complete this lesson.