.strip in Python

Here’s a useful python tip that I use all the time when writing python code, .strip(). This python method call does exactly what you think, it removes extra characters from a string.

Make Money Online Buying Domain Names! Click Here to Find out How

By default it removed white space from the ends. For example, consider this example:

aString = " 123 "
print(len(aString))

Why is the length 5!? This is because there are two extra white space characters, one at the beginning and one at the end. You can get rid of those extra characters like this:

print(len(aString.strip()))

Now the length is 3. Awesome.

Sometimes you need to cleanup a string with more than just white space. Consider this example:

aCrazyString = "  &a line of text& "
# print the string as is
print(aCrazyString)
# remove white space
aCrazyString = aCrazyString.strip()
print(aCrazyString)
# remove '&' characters
aCrazyString = aCrazyString .strip('&')
print(aCrazyString)

All clean now! You should see “a line of text” and only that written in the console.

Increase Your PC Speed With This Great Tool!

Leave a comment