Skip to main content

How to remove whitespace from the beginning and end of a string in Python

How to remove whitespace from the beginning and end of a string in Python.

Here's a step-by-step tutorial on how to remove whitespace from the beginning and end of a string in Python.

  1. First, you need to define the string from which you want to remove the whitespace. Let's say you have a string variable called my_string that contains the text with whitespace.
   my_string = "   Hello, World!   "
  1. To remove the whitespace from the beginning and end of the string, you can use the strip() method. This method removes leading and trailing whitespace characters from a string.
   my_string_stripped = my_string.strip()

The value of my_string_stripped will be "Hello, World!" without any leading or trailing whitespace.

  1. Alternatively, if you only want to remove leading whitespace, you can use the lstrip() method. This method removes whitespace characters from the left side (beginning) of the string.
   my_string_stripped_left = my_string.lstrip()

The value of my_string_stripped_left will be "Hello, World! " without any leading whitespace.

  1. Similarly, if you only want to remove trailing whitespace, you can use the rstrip() method. This method removes whitespace characters from the right side (end) of the string.
   my_string_stripped_right = my_string.rstrip()

The value of my_string_stripped_right will be " Hello, World!" without any trailing whitespace.

It's worth mentioning that the strip(), lstrip(), and rstrip() methods also remove other whitespace characters such as tabs and newline characters besides spaces.

Here's a complete example:

my_string = "   Hello, World!   "
my_string_stripped = my_string.strip()
print(my_string_stripped) # Output: "Hello, World!"

my_string_stripped_left = my_string.lstrip()
print(my_string_stripped_left) # Output: "Hello, World! "

my_string_stripped_right = my_string.rstrip()
print(my_string_stripped_right) # Output: " Hello, World!"

By using any of these methods, you can easily remove whitespace from the beginning and end of a string in Python.