How do I replace whitespaces with underscore?

前端 未结 13 2071

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") 
    
    0 讨论(0)
  • 2020-11-29 16:25

    OP is using python, but in javascript (something to be careful of since the syntaxes are similar.

    // only replaces the first instance of ' ' with '_'
    "one two three".replace(' ', '_'); 
    => "one_two three"
    
    // replaces all instances of ' ' with '_'
    "one two three".replace(/\s/g, '_');
    => "one_two_three"
    
    0 讨论(0)
  • 2020-11-29 16:30

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

    url = "_".join( title.split() )
    
    0 讨论(0)
  • 2020-11-29 16:30
    mystring.replace (" ", "_")
    

    if you assign this value to any variable, it will work

    s = mystring.replace (" ", "_")
    

    by default mystring wont have this

    0 讨论(0)
  • 2020-11-29 16:37

    You can try this instead:

    mystring.replace(r' ','-')
    
    0 讨论(0)
  • 2020-11-29 16:39

    use string's replace method:

    "this should be connected".replace(" ", "_")

    "this_should_be_disconnected".replace("_", " ")

    0 讨论(0)
提交回复
热议问题