How do I replace whitespaces with underscore?

前端 未结 13 2155

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_conn         


        
13条回答
  •  一向
    一向 (楼主)
    2020-11-29 16:24

    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.

提交回复
热议问题