Trimming in Python essentially means removing leading and trailing whitespace from a string. This program shows how to trim a string in Python.
What Is the Need to Trim the White Spaces?
Typically, user input may contain additional white spaces due to typo mistakes, and since Python treats whitespace as a character, it also gets printed with the string. Sometimes, it can also give incorrect results, such as not finding records when searching the database because the keywords do not match due to the extra spaces. Therefore, it is necessary to remove whitespace from strings.
strip() function is of most use as it removes both leading and trailing whitespaces.
str = " String with leading and trailing whitespaces. " print(str.strip())
The above program displays the trim function, the output of which will be something like this:
String with leading and trailing whitespaces.
" Sample string " --> "Sample string" " Sample string" --> "Sample string" "Sample string " --> "Sample string" "Sample string" --> "Sample string"
strip() function also removes tabs and newlines such as
\f, and spaces
str = " Hello world! " print(str.strip(" ")) #it will remove all leading and trailing spaces only. print(str.strip("\n\r")) print(str.strip("-,.")) #It will remove all leading and trailing hyphens, commas, and periods.