Is there a simple way to remove multiple spaces in a string?

后端 未结 29 1466
星月不相逢
星月不相逢 2020-11-22 08:17

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  渐次进展
    2020-11-22 09:20

    import re
    
    Text = " You can select below trims for removing white space!!   BR Aliakbar     "
      # trims all white spaces
    print('Remove all space:',re.sub(r"\s+", "", Text), sep='') 
    # trims left space
    print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='') 
    # trims right space
    print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')  
    # trims both
    print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
    # replace more than one white space in the string with one white space
    print('Remove more than one space:',re.sub(' +', ' ',Text), sep='') 
    

    Result:

    Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar Remove leading space:You can select below trims for removing white space!! BR Aliakbar
    Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar Remove more than one space: You can select below trims for removing white space!! BR Aliakbar

提交回复
热议问题