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

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

Suppose this string:

The   fox jumped   over    the log.

Turning into:



        
29条回答
  •  闹比i
    闹比i (楼主)
    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)))
    

提交回复
热议问题