How to remove leading and trailing whitespaces in Python

Remove leading and trailing whitespaces in Python

In Python, you can remove leading (at the beginning) and trailing (at the end) whitespaces of a string using the str.strip() method.

Removing leading and trailing whitespaces in Python using 'str.strip()' method

1. Create a variable named str_variable and assign string value " Python is a programming language. " to the variable. The string has whitespaces at the both ends.

2. Apply the strip() method to the string variable str_variable. This method removes leading (at the beginning) and trailing (at the end) whitespaces of the string. Store the result in a new variable called strip_string and get the output using print() function.

Please take a closer look at the following example:

Example of using strip() method

Output of the above example
Python is a programming language.

Live Code Playground

In the following Python code editor, you can practice the above code by creating more string variables with leading and trailing whitespaces and remove the leading and trailing whitespaces of the string using str.strip() method. Click on the 'Execute Code' button to execute the code; the executed output will be displayed in the following Python Code Output frame. Practice until you become comfortable and proficient with your code.

Python logo Python Online Editor
Python Code Output