Python trim: Remove Whitespaces From String

Here are ways to trim(remove) whitespaces from a string in Python:

  1. Using strip()
  2. Using lstrip()
  3. Using rstrip()

Whitespace includes all Unicode whitespace characters, such as spaces, tabs (\t), carriage returns (\r), and newlines (\n).

    Method 1: Using strip()

    The strip() method is used to remove leading and trailing whitespaces.

    Visual Representation

    Python trim(Remove) Whitespaces From String Using strip()

    Example

    my_string = " Lee Kuan Yew "
    
    print(my_string)
    
    print(my_string.strip())

    Output

     Lee Kuan Yew 
    Lee Kuan Yew
    

    Method 2: Using lstrip()

    The lstrip() method is used to remove all leading(left-side) whitespaces.

    Visual RepresentationVisual Representation of Using lstrip

    Example

    my_string = " Lee Kuan Yew "
    
    print(my_string)
    
    print(my_string.lstrip())

    Output

         Lee Kuan Yew 
    Lee Kuan Yew 
    

    Method 3: Using rstrip()

    The rstrip() method is used to remove all trailing(right-side) whitespaces.

    Visual RepresentationVisual Representation of Using rstrip()

    Example

    my_string = " Lee Kuan Yew "
    
    print(my_string)
    
    print(my_string.rstrip())

    Output

         Lee Kuan Yew   
         Lee Kuan Yew
    

    Tip: Sometimes, when code is in production mode, coders use the regular expression method re.sub(), which can handle more complex patterns of whitespace.

    Leave a Comment

    This site uses Akismet to reduce spam. Learn how your comment data is processed.