Python Trim String – rstrip(), lstrip(), strip()

Python trim string; Through this tutorial, i am going to show you how to remove whitespace from start and end of string in python using rstrip(), lstrip(), strip() methods.

Python Trim String

To removes spaces from left and right of the string in python; So you can use the following methods to remove or trim string from left and right in python:

  1. Python strip() Trim String :- The strip() method returns a new string after removing (beginning and end) any leading and trailing whitespaces including tabs (\t).
  2. Python trim string from left :- The lstrip() method returns the new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.
  3. Python trim string from Right: It rstrip() method returns the new string with trailing whitespace removed. It’s easier to remember as removing the white spaces from a “right” side of a string.

1: Python strip Trim String

Python strip() in-built method, which is used to remove all the leading and trailing spaces from a string (beginning and end (both sides) of a string).

The syntax of strip() is:

string.strip([chars])

Python strip() Parameters

  • chars (optional) – a string specifying the set of characters to be removed.

If the chars argument is not provided, all leading and trailing whitespaces are removed from the string.

Example 1: python trim string from left and right

str = ' xoxo love xoxo   '
# Leading whitepsace are removed
print(str.strip())
print(str.strip(' xoxoe'))

Output

xoxo love xoxo
lov

2: Python trim string from left

Python lstrip() method returns a copy of the string with leading characters removed (based on the string argument passed). If no argument is passed, it removes leading spaces.

The syntax of lstrip() is:

string.lstrip([chars])

Python lstrip() Parameters

  • chars (optional) – a string specifying the set of characters to be removed.

If the chars argument is not provided, all leading whitespaces are removed from the string.

Example 1: python trim string from left

str = '   this is first left string '
# Leading whitepsace are removed
print(str.lstrip())

Output

this is first left string 

3: Python trim string from Right

python rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces.

The syntax of rstrip() is:

string.rstrip([chars])

Python rstrip() Parameters

  • chars (optional) – a string specifying the set of characters to be removed.

If the chars argument is not provided, all whitspaces on the right are removed from the string.

Example 1: python trim string from right

str = ' this is right side'
# Leading whitepsace are removed
print(str.rstrip())

Output

this is right side

Recommended Python Tutorial

Recommended:-Python Modules
Recommended:-Python Lists
Recommended:-Python Strings

Leave a Comment