Explain Codes LogoExplain Codes Logo

How to replace whitespaces with underscore?

python
regex
functions
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 12, 2025
TLDR

Easily convert spaces to underscores in Python using the replace() method:

output = "Like Python, spaces can also shed their skin".replace(" ", "_")

We're using Python's built-in replace() method. " " is the old skin (spaces), and "_" is the new skin (underscore), Python takes care of the transformation.

Handle multiple types of whitespace

Diversify your whitespace handling game when you have varying types of whitespace characters, such as tabs (\t) or newlines (\n) using re module:

import re output = re.sub('\s', '_', "Spaces, I've gone_rogue\twith\nwhitespaces")

The \s in regex is like the Avengers, bringing together different whitespace heroes under one roof, matching any whitespace characters, and replacing them with underscores.

Django's Slugify: Make URLs Cool Again

Sprucing up URL-friendly formats in Django? Let django.utils.text.slugify do the magic. It converts whitespace to dashes, not underscores (because, you know, making URLs SEO cool is a thing):

from django.utils.text import slugify output = slugify("This is where spaces go on vacation")

To get underscores instead of dashes, cook up this custom function :

def custom_slugify(message): return slugify(message).replace('-', '_') output = custom_slugify("Spaces need a break too")

Split, Join, Repeat

Presenting a simple workaround that doesn't need regex - using split() and join() to replace spaces with underscores while CompactDisc-ing (compact-disc-ing, get it?) extra whitespaces:

output = "_".join("Spaces love to multiply".split())

Surgeon for URL-hostile characters

When dealing with URLs, spaces aren't your only problem. Get rid of those URL-hostile characters to enhance user experience and SEO:

def clean_url(message): return re.sub('\W+', '_', message).lower() output = clean_url("Spaces/grouped with @#$% special_chars")

This function replaces not just whitespaces, but any non-word characters with underscores. It also turns everything lowercase, the perfect recipe for SEO-friendly URLs.

Simplify with reusable functions

Write once, replace everywhere. Use a custom function for consistency in your code, because who likes rewriting, right?

def replace_with_love(message, replace_with='_'): return re.sub('\s+', replace_with, message) output = replace_with_love("Spaces are often misunderstood")

Now you can replace whitespaces with underscores, or any character. Repurpose this function across your application for consistency.

Don’t forget different whitespace characters

Remember, not all whitespaces are born equal. Some texts may contain tabs, newlines, or other invisible characters. Regular expressions save the day again with \s+.