How to remove whitespace from a string in Python

Updated at 06-Jan-2022, By samar

How to remove whitespace from a string in Python

Through many examples, we will learn how to resolve the "How to remove whitespace from a string in Python".

You can remove whitespace from a string in Python using strip() method. strip method removes whitespace characters from both the beginning and end of a string. You can use lstrip() mrthod to remove the whitespace from the beginning of string and rstrip() to remove from the end of a string.
  • Remove whitespace from a string in Python using strip() method

    x = '  Hello python  '.strip()
    print(x)
    

    Output:

    Hello python

    strip() will help you to remove the whitespace from both beginning and end of a string.

  • Remove whitespace from string using replace() method in Python

    x = '  Hello python  '
    print(x.replace(" ", ""))
    

    Output:

    Hellopython

    You can use replace method to replace all the whitespaces with a specific character just by passing the value to second argument or just remove all the spaces by passing value to second argument as the code snippet.

  • Remove whitespace using split and join method in Python

    x = ' Hello python'
    print("".join(x.split()))
    

    Output:

    Hellopython

    You can use split method with the join method to remove all the whitespaces present in a string.

  • Remove whitespace from string using regular expressions in Python

    import re 
    
    x = ' Hello python'
    my_pattern = re.compile(r'\s+')
    print(re.sub(my_pattern, '', x)) 
    

    Output:

    Hellopython

    Regular expressions are used to define a pattern that can be applied to a string. Here we have define the pattern to remove the extra whitespace from the string.

Back to code snippet queries related python