Python remove spaces

Question

Answers ( 1 )

  1. It's a question about how to remove spaces from strings in Python.

    There are several methods to remove spaces from strings in Python:

    1. Using str.replace() method: This method replaces all occurrences of a specified phrase with another specified phrase. Here you can replace spaces with nothing.

      text = "Hello World"
      no_spaces = text.replace(" ", "")
      print(no_spaces)  # Output: HelloWorld
      
    2. Using str.strip() method: This method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove).

      text = " Hello World "
      stripped_text = text.strip()
      print(stripped_text)  # Output: "Hello World"
      

      Note: strip() only removes leading and trailing spaces, not those in between words.

    3. Using str.split() and str.join() methods: This method splits the string into a list where each word is a list item, then joins these items with a specified character. Here we use no character to join, effectively removing spaces.

      text = "Hello World"
      split_text = text.split()
      joined_text = "".join(split_text)
      print(joined_text)  # Output: HelloWorld
      
    4. Using Regular Expressions: For more complex patterns or whitespace removal (like tabs, newlines), you can use the re module.

      import re
      text = "Hello World"
      no_spaces = re.sub(r"\s+", "", text)
      print(no_spaces)  # Output: HelloWorld
      

      The "\s+" pattern targets all whitespace characters (spaces, tabs, newlines) and re.sub replaces them with an empty string.

    These are the common methods to remove spaces in Python. The choice of method depends on the specific requirement, like whether you need to remove all spaces or just leading and trailing spaces.

Leave an answer