Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Remove All Spaces

Remove ordinary space characters with replace. Students follow substring replacement with empty text and distinguish a literal space from tabs or all whitespace.

BeginnerPhase 5 - Category 1: Basic String HandlingExample 9 of 10
remove-all-spaces.py
1# Take string input
2s = input("Enter a string: ")
3
4# Remove spaces
5no_spaces = s.replace(" ", "")
6print(f"Without spaces: {no_spaces}")

Output

Enter a string: Hello World
Without spaces: HelloWorld

In this one

  • Replace literal spaces
  • Use an empty replacement
  • Distinguish tabs from spaces

How it works

  1. 1

    Read the source string.

  2. 2

    Call replace with ordinary space and empty text.

  3. 3

    Print the returned no_spaces result.

Edge cases

What if the input is all spaces?

What if the input is all spaces?

The result is empty.

Are tabs removed too?

Are tabs removed too?

No. They are different characters.

What's going on

replace(" ", "") creates a string without ordinary spaces. The empty replacement contributes no characters for each matched space.

All nonoverlapping space matches are removed, so a b c becomes abc. Tabs, newlines within an existing string, and other whitespace characters do not match the literal space. s itself remains unchanged because replace returns a new string.

What if the input is all spaces? The result is empty.

Are tabs removed too? No. They are different characters.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use an empty replacement?

Pick an answer to check it.

Question 2

What if the input is all spaces?

Pick an answer to check it.

Questions people ask

What if the input is all spaces?

The result is empty.

Are tabs removed too?

No. They are different characters.

Why use an empty replacement?

It deletes each matched space.