Intern
How to remove all spaces from a string?
sobes.tech AI
Answer from AI
Use the replace() method.
# Remove all spaces in a string
my_string = "This is a string with spaces"
string_without_spaces = my_string.replace(" ", "")
Use the split() method with subsequent join().
# Split the string by spaces and join without them
my_string = "Another string with spaces"
string_without_spaces = "".join(my_string.split())
Use regular expressions.
import re
# Remove all whitespace characters using regex
my_string = " String\twith\nvarious spaces "
string_without_spaces = re.sub(r'\s+', '', my_string)
Comparison of methods:
| Method | Description | When to use |
|---|---|---|
replace(" ", "") |
Removes only regular spaces. | A simple case when you need to remove only standard spaces. |
"".join(str.split()) |
Removes sequences of spaces. | Convenient for removing multiple consecutive spaces. |
re.sub(r'\s+', '', str) |
Removes any whitespace characters (\s). |
For removing spaces, tabs, newlines, etc. |