Skip to content
techskilldaily.
The archiveNo. 007
A little Python

Trim the space you didn’t mean to type.

Clean the edges of a text value without changing the words inside.

2 min read 5 min to try
MAKE ROOM FORoneSMALL SKILL

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

Original

␠␠Mina Patel␠␠

After strip()

Mina Patel

The ␠ symbols illustrate spaces; they are not literal input.

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.

A small example to try
raw = "  Mina Patel  "
clean = raw.strip()
print(repr(raw))
print(repr(clean))
Your turn 5 minutes

Make it yours.

  1. Run the example.
  2. Compare the spaces inside the printed quotation marks.
  3. 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.

Keep this bit

Clean only the part you intend to change.

Read more: Python · String methods ↗

No submission needed. This one is just for you.