How can I remove whitespace from the beginning and end of a string in Python?
Gable E
gable e profile pic

In Python, you can remove whitespace characters (spaces, tabs, newlines) from the beginning and end of a string using different approaches. Here's a detailed explanation of a few commonly used methods: Using the strip() method: Thestrip() method is a built-in string method that removes leading and trailing whitespace characters from a string.

1
2
3
4
5
6

my_string = "   Hello, World!   "

trimmed_string = my_string.strip()

print(trimmed_string)  # Output: "Hello, World!"

In this example,my_string.strip() removes the leading and trailing whitespace characters from the stringmy_string, resulting in the trimmed string. The trimmed string is then assigned to the variabletrimmed_string. Using lstrip() and rstrip() methods: Alternatively, you can use thelstrip() method to remove leading whitespace characters from the beginning of the string, or therstrip() method to remove trailing whitespace characters from the end of the string.

1
2
3
4
5
6
7
8

my_string = "   Hello, World!   "

left_trimmed_string = my_string.lstrip()
right_trimmed_string = my_string.rstrip()

print(left_trimmed_string)   # Output: "Hello, World!   "
print(right_trimmed_string)  # Output: "   Hello, World!"

In this example,my_string.lstrip() removes the leading whitespace characters, andmy_string.rstrip() removes the trailing whitespace characters from the stringmy_string. The resulting left-trimmed and right-trimmed strings are assigned to the variablesleft_trimmed_string andright_trimmed_string, respectively. Using regular expressions: You can also use regular expressions (regex) to remove whitespace characters from the beginning and end of a string using there module.

1
2
3
4
5
6
7
8

import re

my_string = "   Hello, World!   "

trimmed_string = re.sub(r'^\s+|\s+$', '', my_string)

print(trimmed_string)  # Output: "Hello, World!"

In this example,re.sub(r'^\s+|\s+$', '', my_string) removes any leading (^\s+) or trailing (\s+$) whitespace characters from the stringmy_string using there.sub() function. It's important to note that all these methods remove only the leading and trailing whitespace characters, not the ones within the string. If you want to remove all whitespace characters, including those within the string, you can use thereplace() method or regular expressions with appropriate patterns. Choose the method that best suits your needs based on the specific requirements of your program.