You don't need regular expressions. Python has a built-in string method that does what you need:

mystring.replace(" ", "_")
Answer from rogeriopvl on Stack Overflow
🌐
CodeFatherTech
codefather.tech β€Ί home β€Ί blog β€Ί how do you remove spaces from a python string?
How Do You Remove Spaces From a Python String? - CodeFatherTech
June 27, 2025 - There are multiple ways to remove spaces from a Python string. The simplest approach is to use the string replace() method. If the spaces to remove are just at the beginning and at the end of the string the strip() method also works fine. An alternative approach is to use a regular expression.
🌐
Caasify
caasify.com β€Ί home β€Ί blog β€Ί master python string handling: remove spaces with strip, replace, join, translate
Master Python String Handling: Remove Spaces with Strip ...
October 5, 2025 - With the re.sub() function, you can set up patterns to match any kind of whitespace and replace it with whatever you want (or nothing at all, if you’re just looking to delete it).
Discussions

python - How to replace whitespaces with underscore? - Stack Overflow
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: "This should be connected" Should become "This_should_be_connected" I am u... More on stackoverflow.com
🌐 stackoverflow.com
python - Replace spaces in string - Code Review Stack Exchange
See similar questions with these tags. ... Lights, camera, open source! Black box AI drift: AI tools are making design decisions nobody asked for ... 5 Minimum amount of spaces inserted in a given string, such that it gets composed only of elements from a given list More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
April 23, 2016
Python 3 - can't delete a space in a string using replace - Stack Overflow
I am running into a weird problem. I load all usernames from the database, then I replace any space found in the username with nothing, so it gets remove. but it's not working, the space stays th... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
methods to remove spaces from text
You are missing a regex. And the best one is number 1. Because of readability. Plus numbers 2, 3 and 4 don't work. You are putting the space back. More on reddit.com
🌐 r/learnpython
16
6
December 20, 2023
🌐
Codingem
codingem.com β€Ί home β€Ί how to remove spaces from string in python
How to Remove Spaces from String in Python - codingem.com
July 10, 2025 - To use Regular Expressions in Python to remove white spaces from a string: Import the regex module, re, to your project. Define a regex pattern that matches white spaces. Substitute each white space with a blank space using re.sub() method. ... import re string = "This is a test" # Regular expression that matches each white space whitespace = r"\s+" # Replace all mathces with an empty string nospaces = re.sub(whitespace, "", string) print(nospaces)
🌐
DigitalOcean
digitalocean.com β€Ί community β€Ί tutorials β€Ί python-remove-spaces-from-string
Effective Ways to Remove Spaces from Strings in Python | DigitalOcean
July 11, 2025 - The strip() method is used to remove whitespace from the start and end of a string. For removing whitespace from the entire string, replace() can be used, and for more sophisticated patterns, you can use regular expressions via the re module. When using print() with multiple arguments, Python ...
🌐
Scaler
scaler.com β€Ί home β€Ί topics β€Ί how to remove whitespace from string in python?
How To Remove Spaces from a String in Python? - Scaler Topics
February 14, 2024 - To eliminate spaces from a string in Python effectively, NumPy offers a straightforward and efficient approach. By utilizing the np.char.replace function, you can seamlessly replace all occurrences of spaces with an empty string, thus removing them from the string.
🌐
Tutorial Gateway
tutorialgateway.org β€Ί python-program-to-replace-blank-space-with-hyphen-in-a-string
Python Program to Replace Blank Space with Hyphen in a String
December 19, 2024 - In this program program, we used For Loop to iterate each character in a String. Inside the For Loop, we are using the If Statement to check whether the String character is empty or blank space. If true, Python will replace it with _.
Find elsewhere
🌐
Sentry
sentry.io β€Ί sentry answers β€Ί python β€Ί remove whitespace from a string in python
Remove whitespace from a string in Python | Sentry
3 weeks ago - my_string = " Hello World !" my_string_no_spaces = my_string.replace(" ", "") print(my_string_no_spaces) # will print "HelloWorld!" To remove all whitespace characters – not just regular spaces but also tabs, non-breaking spaces, hair-width spaces, etc. – we can import Python’s Regular Expressions module and use re.sub with r"\s", a regular expression that will match any whitespace character.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί methods to remove spaces from text
r/learnpython on Reddit: methods to remove spaces from text
December 20, 2023 -

Hi everyone, I recently took the Fullstack Python Developer course and am now taking my first steps on this path.
Can you tell me what other methods of removing spaces from text you know and in which case, each of them is better to use?
So far I know 4 of them:

  1. replace method -> text_wo_spaces = text.replace(" ","")

  2. join and split methods -> text_wo_spaces = ' '.join(text.split())

  3. list generator + join -> text_wo_spaces = ' '.join([char for char in text if char != ' '])

  4. filter + join methods -> text_wo_spaces = ' '.join(filter(lambda char : != ' ', text))

🌐
Python Morsels
pythonmorsels.com β€Ί remove-spaces
How to remove spaces in Python - Python Morsels
January 25, 2022 - The string join method can join an iterable of strings by a delimiter (see convert a list to a string in Python). If we join with a delimiter of empty string (""), we'll effectively remove all spaces: >>> no_spaces = "".join(version.split()) >>> no_spaces 'py310' If you're comfortable with regular expressions, you can also use a regular expression to replace all consecutive whitespace by an empty string:
🌐
Sanfoundry
sanfoundry.com β€Ί python-program-take-string-replace-blank-hyphen
Python Program to Replace Every Blank Space with Hyphen in a String - Sanfoundry
May 30, 2022 - 2. The replace function replaces all occurrences of β€˜ β€˜ with β€˜-β€˜ and store it back in the same variable. 3. The modified string is printed. ... Case 1: Enter string:hello world Modified string: hello-world Case 2: Enter string:apple orange banana Modified string: apple-orange-banana Β· Sanfoundry Global Education & Learning Series – 1000 Python Programs.
🌐
Medium
medium.com β€Ί @bugsanalyze β€Ί how-to-replace-whitespaces-with-underscore-without-using-replace-function-in-python-3b7de422add6
How to replace whitespaces in A String with underscore without using replace function in python? | by G vamsi venkatesh | Medium
August 9, 2022 - In the above syntax pos is the index at which we replace empty space with _. Below is the example code. string = 'Lets start coding in python' for pos in range(0, len(string)): if(string[pos]==' '): string = string[:pos] + '_' + string[pos+1:] print(string)
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί replace single character in string with space
r/learnpython on Reddit: Replace single character in string with space
September 8, 2016 - keep in mind that if you have multiple space in the input string, the output will have only one space between them: "i amSSgood boy" -> "am good boy" (double space after am, written as SS)
🌐
w3resource
w3resource.com β€Ί python-exercises β€Ί re β€Ί python-re-exercise-23.php
Python: Replace whitespaces with an underscore and vice versa - w3resource
import re text = 'Python Exercises' text =text.replace (" ", "_") print(text) text =text.replace ("_", " ") print(text)
🌐
DEV Community
dev.to β€Ί bugsanalyze β€Ί how-to-replace-whitespaces-in-a-string-with-underscore-without-using-replace-function-in-python-5gab
How to replace whitespaces in A String with underscore without using replace function in python? - DEV Community
August 9, 2022 - In the above syntax pos is the index at which we replace empty space with _. Below is the example code. string = 'Lets start coding in python' for pos in range(0, len(string)): if(string[pos]==' '): string = string[:pos] + '_' + string[pos+1:] print(string)
Top answer
1 of 1
1

I believe, using the tools specially designed for text processing is faster than invoking a script written in a general-purpose interpreted language such as Python.

SED doesn't support Unicode escape sequences, but it is possible to pass the actual characters using command substitution:

sed -i -e "s/ /$(printf '\uE000')/g; s/\(.\)/ \1 /g" file

Perl is my favorite, because it is very flexible. It is also much better for text processing than Python:

The Perl languages borrow features from other programming languages including C, shell script (sh), AWK, and sed... They provide powerful text processing facilities without the arbitrary data-length limits of many contemporary Unix commandline tools,... facilitating easy manipulation of text files.

(from Wikipedia)

Example:

perl -CSDL -p -i -e 's/ /\x{E000}/g ; s/(.)/ \1 /g' file

Note, the -CSDL option enables UTF-8 for the output.

There is also an AWKward way of doing this using GNU AWK version 4.1.0 or newer:

gawk -i inplace '{
a = gsub(/ /, "\xee\x80\x80");
a = gensub(/(.)/, " \\1 ", "g");
print a; }' file

But I wouldn't recommend for obvious reasons.

I doubt that anyone would claim that a specific tool, or algorithm is the fastest one, as there are plenty of factors that may affect the performance, - hardware, the way the tools are compiled, tool versions, the kernel version, etc. Perhaps, the best way to find the right tool, or algorithm is to benchmark. I don't think it necessary to mention the time command.

🌐
Quora
quora.com β€Ί How-do-you-remove-all-whitespace-from-a-Python-string
How to remove all whitespace from a Python string - Quora
Answer (1 of 5): Using the re module: [code py] import re string_without_whitespace = re.sub(r"\s+", "", string_with_whitespace) [/code] If you're calling 'sub' very often (in a loop, let's say), you can use a compiled pattern to save a bit of cpu: [code py] pattern = re.compile(r"\s+") string_w...