How do I replace whitespaces with underscore?

Lucas picture Lucas · Jun 17, 2009 · Viewed 330.4k times · Source

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?

Answer

rogeriopvl picture rogeriopvl · Jun 17, 2009

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

mystring.replace(" ", "_")