python – How to replace whitespaces with underscore?

python – How to replace whitespaces with underscore?

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

mystring.replace( , _)

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[^ws], , s)

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

    return s

# Prints: I-cant-get-no-satisfaction
print(urlify(I cant get no satisfaction!))

python – How to replace whitespaces with underscore?

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

url = _.join( title.split() )

Leave a Reply

Your email address will not be published. Required fields are marked *