How to replace whitespaces with underscore?
Easily convert spaces to underscores in Python using the replace()
method:
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:
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):
To get underscores instead of dashes, cook up this custom function :
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:
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:
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?
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+
.
Was this article helpful?