How to remove spaces from a string in Python

Learn how to remove spaces from a string in Python. Explore methods, tips, real-world uses, and how to debug common errors.

How to remove spaces from a string in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

You will often need to remove spaces from a string in Python. This is a common task for data cleanup and to format user input, and Python offers several efficient methods.

Here, you'll learn several techniques, from replace() to regular expressions. You'll also get practical tips, see real-world applications, and receive debugging advice to master string manipulation.

Basic string replace() method

text = "Hello World! How are you today?"
result = text.replace(" ", "")
print(result)--OUTPUT--HelloWorld!Howareyoutoday?

The replace() method is a straightforward way to substitute characters. It takes two arguments:

  • The substring to find (in this case, a space: " ").
  • The string to replace it with (here, an empty string: "").

This process effectively removes every space. Crucially, replace() returns a new string, leaving the original untouched. This is because strings in Python are immutable, which prevents accidental changes to your source data.

String manipulation techniques

For situations where you need more surgical control than simply removing all spaces, Python offers advanced techniques for replacing characters in strings using replace(), join(), and translate().

Using replace() with specific replacements

text = "Hello World! Multiple spaces."
result = text.replace(" ", "")
print(f"Original: '{text}'")
print(f"Modified: '{result}'")--OUTPUT--Original: 'Hello World! Multiple spaces.'
Modified: 'HelloWorld!Multiplespaces.'

The replace() method is a powerful tool for cleaning up inconsistent whitespace. It doesn't just find single spaces; it targets every instance of the character you specify. In the example, text.replace(" ", "") removes all spaces, collapsing the string completely.

  • This is because the method finds and replaces every single occurrence of " ", even when they're next to each other.

Using string join() with filtering

text = "Python is amazing"
result = "".join(char for char in text if char != " ")
print(result)--OUTPUT--Pythonisamazing

The join() method offers a more granular way to remove spaces when paired with a generator expression. This approach builds a new string from scratch, including only the characters you want when using the join method in Python.

  • The expression (char for char in text if char != " ") loops through the string, yielding each character that is not a space.
  • Then, "".join() takes these characters and concatenates them into a single, new string.

This method is particularly memory-efficient because it processes characters one by one without creating an intermediate list in memory.

Using translate() with character mapping

text = "Remove all spaces from this text"
space_mapping = {ord(" "): None} # Map space to None to remove it
result = text.translate(space_mapping)
print(result)--OUTPUT--Removeallspacesfromthistext

The translate() method offers a highly efficient way to perform character-level substitutions. It operates using a translation table, which is essentially a dictionary mapping the characters to be replaced.

  • You create this table with the ord() function, which returns the Unicode code point of a character.
  • By mapping a character’s code point to None, as in {ord(" "): None}, you instruct Python to delete every instance of that character from the string. This makes it exceptionally fast for removing specific characters.

Advanced and optimized approaches

While the previous methods are powerful, you can gain even more control with regular expressions, filter() with lambda, and the maketrans() method.

Using regular expressions

import re
text = "Spaces with irregular spacing"
result = re.sub(r"\s+", "", text)
print(result)--OUTPUT--Spaceswithirregularspacing

Regular expressions give you surgical precision for finding and replacing text patterns. The re.sub() function is your go-to tool for this, allowing you to target more than just single characters. It’s especially powerful for cleaning up messy, inconsistent spacing in text.

  • The pattern r"\s+" is the key. The \s matches any whitespace character (like spaces, tabs, or newlines).
  • The + quantifier tells the function to find one or more of these whitespace characters grouped together.

By replacing these chunks with an empty string, you efficiently remove all spacing, no matter how irregular.

Using filter() with lambda function

text = "Functional programming approach"
result = "".join(filter(lambda char: char != " ", text))
print(result)--OUTPUT--Functionalprogrammingapproach

For a more functional approach, you can pair filter() with a lambda function. This combination lets you define filtering logic on the fly without writing a separate function. It’s a concise way to process iterables based on a simple condition.

  • The lambda char: char != " " is a quick, one-line function that returns True for any character that isn't a space.
  • filter() applies this test to every character, creating an iterator of only the characters that pass.
  • Finally, "".join() assembles these characters into a new, space-free string.

Using string maketrans() for translation

text = "Advanced translation technique"
translator = str.maketrans("", "", " ") # Third argument specifies chars to delete
result = text.translate(translator)
print(result)--OUTPUT--Advancedtranslationtechnique

The str.maketrans() method is a helper function that simplifies creating a translation table for translate(). It's often more convenient than building a dictionary manually, especially for simple deletions.

  • The key here is the third argument. Any characters you pass in this string are marked for deletion.
  • By calling str.maketrans("", "", " "), you create a translator object that specifically targets spaces.

When you then call text.translate(translator), it applies this rule and efficiently removes all spaces from the original string.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like using replace() or join(), to building complete applications without friction.

Instead of piecing together techniques, you can describe the app you actually want to build and Agent 4 will take it from idea to working product. Agent handles everything—from writing the code to connecting databases and APIs, to deploying it live.

  • A user input sanitizer that automatically strips all whitespace from form fields before processing the data.
  • A data formatting tool that takes messy, space-padded text files and cleans them up for consistent database entry.
  • A content utility that generates URL-friendly slugs from article titles by removing spaces and special characters.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even simple string methods can lead to tricky bugs; here are a few common pitfalls and how to sidestep them.

  • Forgetting strings are immutable. A frequent mistake is calling replace() and expecting the original string to change. Since strings can't be modified in-place, the method returns a new copy, and you must assign this result to a variable to save your changes.
  • Needing limited replacements. If you only want to replace the first few spaces, remember that replace() accepts an optional third argument. This count parameter lets you specify the maximum number of substitutions to make, giving you more control.
  • Getting a TypeError with numbers. You'll get a TypeError if you try to use replace() on a number, as the method is exclusive to strings. The fix is to convert the number to a string with str() first, make your changes, and then convert it back if necessary.

Forgetting that replace() doesn't modify strings in-place

A common mistake is calling replace() and expecting the original string to change. Because strings are immutable, the method returns a new string. If you don't assign this result to a variable, your changes are lost. See what happens below.

text = "Hello World"
text.replace(" ", "-")
print(text) # Still prints with space

The replace() method returns a new string, but the code discards it. The original text variable remains unchanged, so the output is unaffected. The following example demonstrates the correct approach to capture the modified string.

text = "Hello World"
text = text.replace(" ", "-") # Assign result back to variable
print(text) # Now prints "Hello-World"

The solution is to capture the new string returned by replace(). Because Python strings are immutable, the method creates a modified copy instead of changing the original. You save this copy by reassigning it, as in text = text.replace(" ", "-"). Forgetting this is a classic pitfall, especially when manipulating data in loops or functions, so always be mindful of reassigning the results from any string method you use.

Limiting replacements with the replace() count parameter

What if you only want to replace the first space in a string, not all of them? By default, the replace() method is an all-or-nothing tool. The following code demonstrates how it replaces every instance, even when that's not your goal.

text = "Replace only the first space in this sentence"
result = text.replace(" ", "-")
print(result) # Replaces ALL spaces

By default, replace() is indiscriminate and swaps every matching character, which is why every space gets a hyphen. The next example demonstrates how to tell the method exactly how many replacements you want to make.

text = "Replace only the first space in this sentence"
result = text.replace(" ", "-", 1) # Third parameter limits to 1 replacement
print(result) # Only first space is replaced

The solution is to use the optional third argument of the replace() method. This count parameter tells Python the maximum number of substitutions to make. By passing 1, as in text.replace(" ", "-", 1), you limit the change to only the first space found. This gives you fine-grained control when you don't want to alter the entire string, such as when you're cleaning up specific parts of user input or formatting data.

Using replace() with numeric values causes TypeError

The replace() method is exclusively for strings, so you'll hit a TypeError if you try to pass a number as the replacement value. This often happens when formatting text with dynamic data, like a price. See what happens below.

price = 9.99
text = "The price is X dollars"
result = text.replace("X", price) # TypeError: replace() argument must be str
print(result)

The replace() method can't substitute a number directly into a string. Because the price variable isn't a string, Python raises a TypeError. The following code shows the simple fix for this.

price = 9.99
text = "The price is X dollars"
result = text.replace("X", str(price)) # Convert to string first
print(result) # Correctly shows "The price is 9.99 dollars"

The solution is to convert the number to a string using the str() function before passing it to replace(). The method requires all its arguments to be strings, so attempting to substitute a numeric value directly results in a TypeError. You’ll often encounter this when dynamically inserting data like prices or IDs into template strings. Always ensure your replacement value is a string first to prevent the program from crashing.

Real-world applications

After navigating the common pitfalls, you can confidently use these methods for practical tasks like normalizing user input and creating clean web URLs.

Normalizing user input with replace()

User input is often inconsistent, but you can easily normalize it by using strip() to remove leading and trailing whitespace and then calling replace() in a loop to collapse any extra spaces in between.

user_input = " John Doe "
# First trim, then replace double spaces until none remain
normalized = user_input.strip()
while " " in normalized:
normalized = normalized.replace(" ", " ")
print(f"Original input: '{user_input}'")
print(f"Normalized input: '{normalized}'")

This approach tackles inconsistent spacing in two steps. After an initial pass with strip(), the while loop iteratively cleans up the string's interior.

  • The loop's condition, while " " in normalized, checks for any remaining double spaces.
  • Each time it runs, replace(" ", " ") swaps one double space for a single one.
  • This process repeats until all consecutive spaces are collapsed into single spaces, ensuring a consistently formatted result.

Creating slugs for web URLs with replace()

By chaining several replace() calls together, you can easily convert a title into a URL-friendly slug by swapping spaces for hyphens and stripping out punctuation, similar to replacing spaces with underscores. This kind of quick automation work is perfect for vibe coding.

article_title = "How to Use Python's Replace Method!"
slug = article_title.lower().replace(" ", "-").replace("'", "").replace("!", "")
print(f"Article title: '{article_title}'")
print(f"URL slug: '{slug}'")

This example showcases Python's efficient method chaining. Since string methods don't alter the original string but return a new, modified one, you can link them together. The code first converts the article_title to lowercase with lower(). The resulting string is then passed directly to the first replace() call, which swaps spaces. This continues down the chain, with each method refining the output of the last, ultimately creating the final slug in one concise statement.

Get started with Replit

Now, turn what you've learned into a real tool. Just tell Replit Agent what you need: "a tool that cleans user input by removing extra spaces" or "a URL slug generator for blog post titles."

The Agent writes the code, tests for errors, and deploys your app for you. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.