Remove all whitespace in a string

后端 未结 11 1681
一整个雨季
一整个雨季 2020-11-22 04:02

I want to eliminate all the whitespace from a string, on both ends, and in between words.

I have this Python code:

def my_handle(self):
    sentence          


        
11条回答
  •  自闭症患者
    2020-11-22 04:28

    An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:

    Remove ALL spaces in a string, even between words:

    import re
    sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
    

    Remove spaces in the BEGINNING of a string:

    import re
    sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
    

    Remove spaces in the END of a string:

    import re
    sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
    

    Remove spaces both in the BEGINNING and in the END of a string:

    import re
    sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
    

    Remove ONLY DUPLICATE spaces:

    import re
    sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
    

    (All examples work in both Python 2 and Python 3)

提交回复
热议问题