remove trailing spaces

libertycodervice

libertycodervice

Posted on March 4, 2020

remove trailing spaces

If you have a Python text string, and want trailing spaces removed you can do that with the method .strip(), .lstrip() and .rstrip().

That removes the spaces before and after the string.

Example

You can use strip, lstrip, rstrip methods. Like the name suggests, lstrip strips left of the string, rstrip strips right of the string and strip just strips the string of spaces.

First create a string surrounded by spaces:

>>> a = "abc".center(30)
>>> a
'             abc              '
>>>

To do a left strip, call the method lstrip(). This removes spaces to the left of the string:

>>> b = a.lstrip()
>>> b
'abc              '

The results of a right strip, call rstrip() which removes spaces to the right of the string:

>>> 
>>> c = a.rstrip()
>>> c
'             abc'

To do a general strip, that removes all spaces on both sides:

>>> 
>>> d = a.strip()
>>> d
'abc'
>>> 
>>> 

The strip() function only does trailing spaces, not spaces inside the string itself.

>>> a = "    aaaa  bbbb ccc    dddd   eee           "
>>> a.strip()
'aaaa  bbbb ccc    dddd   eee'
>>> 
💖 💪 🙅 🚩
libertycodervice
libertycodervice

Posted on March 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024