How do I replace multiple spaces with just one character?

后端 未结 3 810
孤独总比滥情好
孤独总比滥情好 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:11

    This pattern will replace any groups of whitespace with a single underscore

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

    If you only want to replace spaces (not tab/newline/linefeed etc.) it's probably easier to use a regex

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

提交回复
热议问题