Advertisement
Advertisement


How do I replace whitespaces with underscore?


Question

I want to replace whitespace with underscore in a string to create nice URLs. So that for example:

"This should be connected" becomes "This_should_be_connected" 

I am using Python with Django. Can this be solved using regular expressions?

2020/08/14
1
227
8/14/2020 8:51:37 PM

Accepted Answer

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

mystring.replace(" ", "_")
2017/01/18
386
1/18/2017 12:19:49 AM

Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.

Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.

import re

def urlify(s):

    # Remove all non-word characters (everything except numbers and letters)
    s = re.sub(r"[^\w\s]", '', s)

    # Replace all runs of whitespace with a single dash
    s = re.sub(r"\s+", '-', s)

    return s

# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
2018/10/01

Django has a 'slugify' function which does this, as well as other URL-friendly optimisations. It's hidden away in the defaultfilters module.

>>> from django.template.defaultfilters import slugify
>>> slugify("This should be connected")

this-should-be-connected

This isn't exactly the output you asked for, but IMO it's better for use in URLs.

2009/06/17

This takes into account blank characters other than space and I think it's faster than using re module:

url = "_".join( title.split() )
2012/04/29

Using the re module:

import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this

Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace as others have suggested.

2009/06/17

use string's replace method:

"this should be connected".replace(" ", "_")

"this_should_be_disconnected".replace("_", " ")

2009/06/17

Source: https://stackoverflow.com/questions/1007481
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]