collapsing whitespace in a string

后端 未结 6 1850
隐瞒了意图╮
隐瞒了意图╮ 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:40

    s = "$$$aa1bb2 cc-dd ee_ff ggg."
    re.sub(r'\W+', ' ', s).upper()
    # ' AA1BB2 CC DD EE_FF GGG '
    

    Is _ punctuation?

    re.sub(r'[_\W]+', ' ', s).upper()
    # ' AA1BB2 CC DD EE FF GGG '
    

    Don't want the leading and trailing space?

    re.sub(r'[_\W]+', ' ', s).strip().upper()
    # 'AA1BB2 CC DD EE FF GGG'
    

提交回复
热议问题