Skip to content

Remove leading and trailing spaces in Python | Example code

  • by

Use the strip() method to remove trailing and leading spaces in Python. It will not remove internal spaces in a string.

Remove leading and trailing spaces in Python Example

Simple example code eliminates all whitespace before the first character and after the last character in the string.

It will actually trim all leading and trailing whitespace from the string.

test_str = "   ABC DEF   "

res = test_str.strip()

print(res)

Output:

Do comment if you have any doubts and suggestions on this python space topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *