Trim Whitespace from Strings

Learn to trim whitespace from strings.

We'll cover the following

It is common for input from users to include extraneous whitespaceExtraneous whitespace refers to unnecessary or redundant spaces, tabs, or line breaks within text or code that do not contribute to its meaning or functionality. at one or both ends of a string. This can be problematic, so we often need to remove it. In this recipe, we'll use the string class methods, find_first_not_of() and find_last_not_of(), to trim whitespace from the ends of a string.

How to do it

The string class includes methods for finding elements that are, or are not, included in a list of characters. We'll use these methods to trim string:

  • We start by defining string with input from a hypothetical ten-thumbed user:

Get hands-on with 1400+ tech skills courses.