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.
1# Take string input2s = input("Enter a string: ")34# Remove spaces5no_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
Read the source string.
- 2
Call replace with ordinary space and empty text.
- 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.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum