How do I replace whitespaces with underscore?

前端 未结 13 2168

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

    Surprisingly this library not mentioned yet

    python package named python-slugify, which does a pretty good job of slugifying:

    pip install python-slugify
    

    Works like this:

    from slugify import slugify
    
    txt = "This is a test ---"
    r = slugify(txt)
    self.assertEquals(r, "this-is-a-test")
    
    txt = "This -- is a ## test ---"
    r = slugify(txt)
    self.assertEquals(r, "this-is-a-test")
    
    txt = 'C\'est déjà l\'été.'
    r = slugify(txt)
    self.assertEquals(r, "cest-deja-lete")
    
    txt = 'Nín hǎo. Wǒ shì zhōng guó rén'
    r = slugify(txt)
    self.assertEquals(r, "nin-hao-wo-shi-zhong-guo-ren")
    
    txt = 'Компьютер'
    r = slugify(txt)
    self.assertEquals(r, "kompiuter")
    
    txt = 'jaja---lol-méméméoo--a'
    r = slugify(txt)
    self.assertEquals(r, "jaja-lol-mememeoo-a") 
    

提交回复
热议问题