Trim the space you didn’t mean to type.
Clean the edges of a text value without changing the words inside.
An invisible character is still a character.
You copy a name into a form and later discover it does not match the same name elsewhere. A space at the beginning or end can be hard to see. Python’s strip() method returns a version of a string with surrounding whitespace removed.
Try the short example below. repr() makes the original edges easier to spot because it puts quotation marks around the displayed value. The spaces before and after Mina are part of the original text.
Text cleanup
␠␠Mina Patel␠␠
Mina Patel
Keep the original when you need it.
Strings are not edited in place by strip(). The cleaned result needs its own variable, or you can assign it back to the same name. In this exercise, keeping both versions lets you compare them.
Whitespace inside the text stays where it is. A person called “Mina Patel” should not become “MinaPatel.” Cleaning is a specific transformation, not permission to discard every space. This is why testing a name with two words is useful.
raw = " Mina Patel "
clean = raw.strip()
print(repr(raw))
print(repr(clean))Make it yours.
- Run the example.
- Compare the spaces inside the printed quotation marks.
- Replace the name with two different words and keep spaces around the outside.
What changed when you tried it?
A little nudge
Print repr() rather than relying on empty space at the edge of a terminal line.
What to look for
The cleaned value is 'Mina Patel'. The space between the words remains, and raw still contains its original outer spaces.
Take it one small step further
Try a tab at the beginning using \t inside the string.
Clean only the part you intend to change.
Read more: Python · String methods ↗
No submission needed. This one is just for you.