How do I replace multiple spaces with just one character?

后端 未结 3 825
孤独总比滥情好
孤独总比滥情好 2020-12-31 18:31

Here\'s my code so far:

input1 = input(\"Please enter a string: \")
newstring = input1.replace(\' \',\'_\')
print(newstring)

So if I put in

3条回答
  •  长发绾君心
    2020-12-31 19:22

    Dirty way:

    newstring = '_'.join(input1.split())
    

    Nicer way (more configurable):

    import re
    newstring = re.sub('\s+', '_', input1)
    

    Extra Super Dirty way using the replace function:

    def replace_and_shrink(t):
        '''For when you absolutely, positively hate the normal ways to do this.'''
        t = t.replace(' ', '_')
        if '__' not in t:
            return t
        t = t.replace('__', '_')
        return replace_and_shrink(t)
    

提交回复
热议问题