Python trim string | Python string strip() function

You can trim string in python using a strip() function. It removes the leading and trailing spaces of a given String. There are 2 more methods “lstrip() and rstrip()” can use to remove leading or trailing whitespaces.

Note: default whitespace characters will remove, you can remove other char also.

Method to trim Stings in Python

  • strip():  removes spaces from the left and right of the string and returns the copy of the string.
  • lstrip(): returns the string after removing leading whitespaces.
  • rstrip(): returns a string after removing the trailing whitespace

Syntax

Parameters

The characters to be removed from beginning or end of the string.

Python strip() example | trim string

Let’s see the examples how to trim string from left, right or all whitespaces.

1. Without chars parameter

The below code displays the working of strip() in various conditions.

Output: Blue color space indicates whitespace.

Python trim string | Python string strip() function

2. Remove “0” from String

Output: this is string trim example….!

3. trim string from Left | lstrip() Python

USE “lstrip() function” to remove left space from sting.

Example

Output: Python lstrip method

4. trim string from Right | rstrip() Python

The rstrip() method removes the trailing (right) spaces from the given string and returns a copy after removing whitespaces from the right side.

Example

Output: Python rstrip method

Q: How to trim string characters in Python?

Answer: Remove ‘www’ and ‘com’ and ‘.’ from the string using a strip() method.

Output: EyeHunts

Q: How to trim all whitespace include between text in python?

Answer: If you noticed the strip method only remove the left and right space or char. So if you want to remove all space from a string you can use replace() method in Python.

Output: abcd

Read More about – Python string replace function Examples

Do comment if you knew any other way to do it. Or have any suggestions Or doubts.

Note:
IDE: PyCharm 2020.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples string.count python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

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