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 that you want to remove whitespace from. Let's say you have the following string:

    my_string = "   Hello, World!   "
  2. To remove whitespace from the beginning and end of the string, you can use the strip() method. This method removes whitespace characters, including spaces, tabs, and newlines, from both ends of the string. To use the strip() method, you can simply call it on your string variable:

    my_string_stripped = my_string.strip()

    In this example, the strip() method will remove the leading and trailing spaces from the my_string, so my_string_stripped will be equal to "Hello, World!".

  3. If you only want to remove whitespace from the beginning of the string, you can use the lstrip() method. This method removes whitespace characters only from the left or beginning of the string. Similarly, you can call the lstrip() method on your string variable:

    my_string_stripped_left = my_string.lstrip()

    In this case, my_string_stripped_left will be equal to "Hello, World! ".

  4. Conversely, if you only want to remove whitespace from the end of the string, you can use the rstrip() method. This method removes whitespace characters only from the right or end of the string. Again, you can call the rstrip() method on your string variable:

    my_string_stripped_right = my_string.rstrip()

    Here, my_string_stripped_right will be equal to " Hello, World!".

  5. If you want to remove specific characters other than whitespace, you can pass them as arguments to the strip(), lstrip(), or rstrip() methods. For example, if you want to remove all commas from the beginning and end of the string, you can modify your code as follows:

    my_string = "   ,Hello, World!,   "
    my_string_stripped_commas = my_string.strip(",")

    In this case, my_string_stripped_commas will be equal to "Hello, World!", with the commas removed.

That's it! You now know how to remove whitespace from the beginning and end of a string in Python using the strip(), lstrip(), and rstrip() methods. Feel free to use the method that suits your specific needs.