collapsing whitespace in a string

后端 未结 6 1880
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 03:59

I have a string that kind of looks like this:

\"stuff   .  // : /// more-stuff .. .. ...$%$% stuff -> DD\"

and I want to strip off all p

6条回答
  •  天命终不由人
    2021-01-05 04:46

    One can use regular expression to substitute reoccurring white spaces. White space is given by \s with \s+ meaning: at least one.

    import re
    rex = re.compile(r'\s+')
    test = "     x  y z           z"
    res = rex.sub(' ', test)
    print(f">{res}<")
    

    > x y z z<

    Note this also affects/includes carriage return, etc.

提交回复
热议问题