Python Programming Examples Tutorial Index

Python String Programs


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.

Python provides three inbuilt functions to trim strings and remove whitespace. These are:
  1. strip()
  2. lstrip()
  3. rstrip()

Mostly, the strip() function is of most use as it removes both leading and trailing whitespaces.

Syntax:
string.strip(string)
Example:
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:

Output:
String with leading and trailing whitespaces.
" Sample string " --> "Sample string"
" Sample string"  --> "Sample string"
"Sample string "  --> "Sample string"
"Sample string"   --> "Sample string"

The strip() function also removes tabs and newlines such as \n, \r, \t, \f, and spaces , so to remove only specific characters, specify it as an argument.

Example:
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.