banner

© 2004-21 ict4u.net

Strip - remove whitespace

This of removes unwanted whitespace (space, tabs etc) from the beginning or end text variables or constants.
This is useful when you want to check user input for specific text string. If they have pressed the space bar after the characters you were expecting the string will not match but it will not be immediately obvious why

# A Knifton
# Demo of cleaning a string of unwanted whitespace
#

myText = " Interesting Parody "
#
print ("Text string to be trimmed: ", myText, " Has a space at either end")
iTextLen = len(myText)
print ("Length of varaible is:  ", iTextLen)
#
#  remove whitespace from the right
myText = myText.rstrip()
print ("Text string has whitespace at the right removed (rstrip): ", myText, " Length=", len(myText))

#  remove whitespace from the left
myText = myText.lstrip()
print ("Text string has whitespace at the right removed (lstrip): ", myText, " Length=", len(myText))

myText = " Interesting Parody "
#  remove whitespace from the right and left
myText = myText.strip()
print ("Text string has whitespace at both ends removed (strip): ", myText, " Length=", len(myText))