Remove leading and trailing spaces in Python | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.