Python Tutorial (33) - Example: Remove leading and trailing spaces from a string

Time: Column:Python views:285

Removing Whitespace from a String in Python

In Python, you can remove leading and trailing spaces from a string using the strip() method. This method is useful for cleaning up text and ensuring that there are no unwanted spaces at the beginning or end of a string.

Here is an example of how to use it:

Example:

original_string = "   This is a string with spaces   "
stripped_string = original_string.strip()
print(stripped_string)

The above code removes the leading and trailing spaces from the string, producing the following output:

This is a string with spaces

However, if the string contains characters like \n (newline), and you only want to remove spaces, you need to explicitly specify spaces in the strip() method, as shown in the following example:

Example:

my_string = " \nPython "

print(my_string.strip(" "))

The output will be:

Python

Using Regular Expressions to Remove Leading and Trailing Spaces

You can also use regular expressions to remove spaces at the beginning and end of a string. This can be helpful if you need more control over which characters to remove.

Example:

import re

my_string = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)

print(output)

The result will be:

Hello Python

The strip() method removes all leading and trailing whitespace characters from a string, including spaces, tabs, and newline characters.

Other Methods to Remove Whitespace

Python also provides two additional methods for removing spaces from specific parts of a string:

  • lstrip() — Removes whitespace from the beginning of the string.

  • rstrip() — Removes whitespace from the end of the string.

Example:

original_string = "   This is a string with spaces   "
left_stripped_string = original_string.lstrip()  # Remove leading spaces
right_stripped_string = original_string.rstrip()  # Remove trailing spaces

print(left_stripped_string)
print(right_stripped_string)

The output will be:

This is a string with spaces   
   This is a string with spaces

These methods allow for more flexibility, depending on whether you want to remove leading, trailing, or both types of whitespace from your string.