How to remove spaces from a string in Python

Struggling with extra spaces in your Python strings? Learn multiple ways to remove them, see real-world examples, and debug common errors.

How to remove spaces from a string in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

You will often need to remove spaces from strings in Python, a common task for data cleaning and formatting. Python provides powerful built-in methods to handle whitespace efficiently.

You'll discover techniques like replace() and split() with join(). You will also find practical tips, see real-world applications, and get advice to debug common whitespace issues.

Basic string replace() method

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

The replace() method offers a direct way to substitute substrings. In this case, text.replace(" ", "") finds every instance of a space character and replaces it with an empty string, which effectively deletes all spaces.

It's important to remember that strings in Python are immutable. The replace() method doesn't alter the original text variable. Instead, it returns a completely new string with the replacements made. You must assign this output to a new variable like result to capture the changes.

String manipulation techniques

While the basic replace() method is a good start, you'll often need more surgical precision, which is where methods like join() and translate() come in.

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 provides a direct way to handle specific characters. When you use text.replace(" ", ""), Python scans the entire string and removes every single space it finds, not just the first one.

  • This is why it works on strings with inconsistent spacing. It doesn't matter if there's one space or several together—they all get replaced.

As you can see, the result is a string with no spaces at all. It’s a simple yet effective technique if your goal is complete removal.

Using string join() with filtering

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

Using join() with a generator expression gives you fine-grained control. This combination iterates through the string and rebuilds it based on a condition you set.

  • The generator, (char for char in text if char != " "), loops through each character.
  • It uses an if condition to check if the character is a space. If it isn't, the character is kept.
  • Then, "".join() takes all the kept characters and connects them into a new string with no spaces.

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 is a powerful tool for making multiple character-level changes at once. It operates using a translation table—a dictionary that maps the characters you want to replace.

  • You use the ord() function to get the unique Unicode number for a character, like a space.
  • By mapping this number to None, you're telling Python to delete that character wherever it appears in the string.

This technique is exceptionally fast, making it a great choice when performance matters, especially for removing several different characters in a single pass.

Advanced and optimized approaches

Beyond the standard methods, Python offers more powerful and optimized tools for tackling complex whitespace challenges with greater precision and speed.

Using regular expressions

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

When you need to handle more than just simple spaces, regular expressions are your best bet. The re.sub() function is a powerful tool for finding and replacing text that matches a specific pattern, giving you much more flexibility than basic string methods.

  • The pattern r"\s+" is the key here. The \s part matches any whitespace character, not just spaces but also tabs and newlines.
  • The + quantifier tells Python to match one or more of these whitespace characters grouped together.

This combination allows you to remove all chunks of whitespace, no matter their length or type, in a single, clean operation.

Using filter() with lambda function

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

This approach offers a more functional style for removing spaces. The filter() function works with a lambda to test each character in the string, giving you a concise way to build a new string based on a condition.

  • The lambda char: char != " " is a small, anonymous function that returns True for any character that is not a space.
  • filter() then creates an iterator that yields only the characters that pass this test.
  • Finally, "".join() stitches these characters back together 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

Using str.maketrans() is a more direct way to build a translation table, especially when you only need to delete characters. It's a helper function that saves you from creating a dictionary by hand.

  • You leave the first two arguments as empty strings ("") since you aren't swapping characters.
  • The third argument, " ", is a string of all characters you want to remove.

The resulting translator object is then used with text.translate() to efficiently remove the specified characters.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

The string manipulation techniques from this article can be the foundation for production-ready tools. Replit Agent can build them for you directly from a description:

  • A data normalization utility that cleans up inconsistent user input or CSV headers by removing all whitespace.
  • A URL slug generator that converts article titles into clean, web-friendly strings for SEO.
  • A simple code minifier that strips extra spaces from scripts to reduce file size.

Describe your app idea, and Replit Agent will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

When removing spaces in Python, you might run into a few common pitfalls that are easy to overlook but simple to fix.

A frequent mistake is calling replace() and expecting your original string to change. Because strings in Python are immutable, the method doesn't modify the variable in place. Instead, it returns a completely new string with the changes applied.

  • To see the result, you must capture this new string by assigning it to a variable, which can even be the same one you started with.

You may not always want to remove every single space. The replace() method has an optional count parameter that gives you control over how many replacements occur. If you leave it out, you'll replace all occurrences, which might be more than you need.

  • For example, using text.replace(' ', '', 1) will only remove the first space it encounters in the string.

Trying to use replace() on a number will stop your code with a TypeError. This error happens because replace() is exclusively a string method and doesn't work on numeric types like integers or floats.

  • The solution is to convert the number to a string first using the str() function before you attempt any replacements.

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

It's a classic slip-up: you call the replace() method, but your string looks exactly the same. This happens because strings are immutable—they can't be changed. The method actually returns a new string. Check out what happens when you forget to capture it.

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

The text.replace() call successfully creates a new string, but its result is discarded. Since the original text variable isn't reassigned, print(text) still outputs the unchanged string. The corrected code below shows how to capture the result.

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

The fix is to capture the new string returned by replace(). You do this by reassigning the result back to a variable, which can be the original one.

  • The line text = text.replace(" ", "-") effectively updates the text variable with the modified string.

This pattern is essential when working with immutable data types. It ensures your changes are saved, so always remember to reassign the output when you expect a variable to be updated.

Limiting replacements with the replace() count parameter

Sometimes you don't want to remove every space. The replace() method's default behavior can be too aggressive, changing more of your string than intended. Forgetting the optional count parameter is a common oversight. See what happens in the code below.

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

Without any limits, the replace() method swaps every space for a hyphen, altering the entire sentence. The corrected code below demonstrates how to specify which 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 fix is to use the optional third argument in the replace() method. By passing 1 as the count parameter, you're telling Python to stop after making just one replacement. This gives you precise control over your string modifications.

  • This is useful when you only want to change the beginning of a string—like swapping the first space for a hyphen—without altering the rest of the sentence.

Using replace() with numeric values causes TypeError

It's a common mistake to mix data types with replace(). This method is exclusively for strings, so using a number as a replacement value will trigger a TypeError. Python expects all arguments to be strings. The code below demonstrates this error.

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

The TypeError happens because you're trying to substitute a placeholder with the numeric price variable. The replace() method can only work with strings. The corrected code below shows how to resolve this type conflict.

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 fix is to convert the number to a string before making the replacement. The replace() method strictly requires string arguments, which is why passing a number causes a TypeError. Using str(price) gives the method the string representation it needs to work correctly.

  • It's a common step when you're inserting dynamic data, like prices or counts, into template strings. Always ensure your data types match what the method expects.

Real-world applications

Beyond the technical methods, removing spaces is a key skill for practical tasks like cleaning user input and creating web-friendly URLs.

Normalizing user input with replace()

You can easily normalize messy user input, which often contains extra leading, trailing, or internal spaces, by using a combination of strip() and replace() to create a clean, consistent string.

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 code snippet cleans up erratic spacing by first calling user_input.strip() to remove any whitespace from the start and end of the string. The core of the logic is the while loop, which tackles inconsistent spaces between words.

  • The loop continues as long as a double space, "  ", is found in the string.
  • Inside the loop, normalized.replace("  ", " ") substitutes every double space with a single one.

This iterative process ensures that even three or more consecutive spaces are eventually reduced to just one, creating a uniformly formatted string.

Creating slugs for web URLs with replace()

You can also chain multiple replace() calls to quickly turn a post title into a clean, URL-friendly slug by swapping spaces and removing punctuation.

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 code efficiently transforms a string by chaining several methods together in one line. The output of each method becomes the input for the next, creating a sequential flow of operations.

  • It begins by converting the entire string to lowercase with lower().
  • Next, replace(" ", "-") swaps all spaces with hyphens.
  • Finally, two more replace() calls strip out the apostrophe and exclamation mark by substituting them with nothing.

This technique is a concise way to apply multiple modifications to a string without needing intermediate variables.

Get started with Replit

Now, turn what you've learned into a real tool. Just tell Replit Agent to "build a utility that normalizes CSV headers by removing all whitespace" or "create a script that cleans user tags."

It will write the code, test for errors, and deploy your app from that simple description. All you need is the idea. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.