Be cautious on Python strip on string

One day my colleague came to me by saying that “Bro, I am getting a weird behavior on strip() in Python”. Then we sat together and got few points related to strip method which are very important. I am sharing those here for you guys to make a note. Let’s see that in detail.

Guess what would be the result of the below snippet.

If you guessed that the output as “test_file”, then guess for the below statement as well.

if your guess is “test_file_for_arockia”, you are wrong. The actual output is “test_file_for_arocki”.  Just give a try in Python shell :). Assumption we are having here is,

  1. remove the mentioned pattern in a text at the beginning or end of the string and lstrip, rstrip behaves left, right match respectively.

But the strip method evaluates bit different manner. Now let’s look into the actual behavior.

  1. charset we mention in strip method will be considered as a set of individual characters.
  2. If there is a combination of the characters at the beginning or end of string will be stripped off

Now let’s see the below examples to look for the proper behavior

Example 1:

Output: lication_test_for_arocki

From this example, we are able to see that it stripped of the combination pattern “app” at the beginning and “a.apk” at the end.

Example 2:

Output: lication_test_for_aroc

From the above example, It stripped of “app”,”k.apk” from beginning, end respectively.

Example 3:


From this code, observe that <,> stripped off since we mentioned both characters in the pattern.

So, when you use strip method to remove the pattern, be little cautious on the pattern.

Sharing is caring!

Arockia Arulnathan

Constant Learner |Blog writer | Tech enthusiast

You may also like...

Leave a Reply