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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
相关标签:
29条回答
  • 2020-11-22 09:16
    string = 'This is a             string full of spaces          and taps'
    string = string.split(' ')
    while '' in string:
        string.remove('')
    string = ' '.join(string)
    print(string)
    

    Results:

    This is a string full of spaces and taps

    0 讨论(0)
  • 2020-11-22 09:17

    I have to agree with Paul McGuire's comment. To me,

    ' '.join(the_string.split())
    

    is vastly preferable to whipping out a regex.

    My measurements (Linux and Python 2.5) show the split-then-join to be almost five times faster than doing the "re.sub(...)", and still three times faster if you precompile the regex once and do the operation multiple times. And it is by any measure easier to understand -- much more Pythonic.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:20

    I haven't read a lot into the other examples, but I have just created this method for consolidating multiple consecutive space characters.

    It does not use any libraries, and whilst it is relatively long in terms of script length, it is not a complex implementation:

    def spaceMatcher(command):
        """
        Function defined to consolidate multiple whitespace characters in
        strings to a single space
        """
        # Initiate index to flag if more than one consecutive character
        iteration
        space_match = 0
        space_char = ""
        for char in command:
          if char == " ":
              space_match += 1
              space_char += " "
          elif (char != " ") & (space_match > 1):
              new_command = command.replace(space_char, " ")
              space_match = 0
              space_char = ""
          elif char != " ":
              space_match = 0
              space_char = ""
       return new_command
    
    command = None
    command = str(input("Please enter a command ->"))
    print(spaceMatcher(command))
    print(list(spaceMatcher(command)))
    
    0 讨论(0)
  • 2020-11-22 09:20

    I have my simple method which I have used in college.

    line = "I     have            a       nice    day."
    
    end = 1000
    while end != 0:
        line.replace("  ", " ")
        end -= 1
    

    This will replace every double space with a single space and will do it 1000 times. It means you can have 2000 extra spaces and will still work. :)

    0 讨论(0)
提交回复
热议问题