How do I replace whitespaces with underscore?

前端 未结 13 2181

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

    Using the re module:

    import re
    re.sub('\s+', '_', "This should be connected") # This_should_be_connected
    re.sub('\s+', '_', 'And     so\tshould this')  # And_so_should_this
    

    Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace as others have suggested.

提交回复
热议问题