How do I replace whitespaces with underscore?

前端 未结 13 2160

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:14

    I'm using the following piece of code for my friendly urls:

    from unicodedata import normalize
    from re import sub
    
    def slugify(title):
        name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
        #remove `other` characters
        name = sub('[^a-zA-Z0-9_-]', '', name)
        #nomalize dashes
        name = sub('-+', '-', name)
    
        return name
    

    It works fine with unicode characters as well.

提交回复
热议问题