Udit Vashisht
Author: Udit Vashisht

Python 3 useful tip-strip()-A useful built-in type.

  • 2 minutes read
Python 3 useful tip-strip()-A useful built-in type.

Have you ever stumbled across a set of data that contains an extra underscore, character, or word as prefix or suffix, which you want to get rid of?

Python is known for having a resourceful standard library with lots of built-in types that can do a set of tasks in a jiffy. One such built-in type is str.strip([chars]). This built-in type in theory omits the set of characters given as an argument from the beginning and end of string. If no character argument is given, it removes the whitespace from the string. One of the example of the usage is as under:-

example_string = '    anexamplestring    '


However, if we add certain characters in ‘char’ arguments, those characters will be removed from the beginning and end of the string until a character not given in the argument is reached on both side of the string. Example as under:-

example_string = '123_ab_1cde_3'


It must be noticed that the .strip() function stop deleting the characters from either side as soon as it reaches a character which is not passed in the argument. And, it will not remove the characters thereafter even if they are the one passed in the argument as in example above, once the strip() reaches the character ‘a’ moving from left to right, it stopped removing character and didn’t effect ‘_’ and ‘1’ thereafter. Similarly, strip() moving from right to left encounters character ‘e’ and stop functioning thereafter.

Related Posts

Python Logging Module - A Primer
By Udit Vashisht

Logging in python

Logging is the module in the standard library of python. Logging is an important tool for a programmer or developer, as it gives more insights about the code and any errors in it. In this tutorial, we will learn all about the python logging module. ...

Read More
Set Passwords and Secret Keys in Environment Variables (Mac/Linux/Windows) - Python Quicktip
By Udit Vashisht

Hide Passwords and Secret Keys in Environment Variables

If you are into python , there is a fair chance that you would have contributed to open-source or had your code snippets/projects on Github or BitBucket.Some time your code involves some important credentials like passwords or secret keys ...

Read More
Nested List to list - Python in just three lines of code
By Udit Vashisht

Nested list to list in Python

Nested list in python can be converted to a flat list in python in just three lines of code. Let us assume that you have a following nested list.

[1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]

Now, the above list ...

Read More