What is the difference between strip() and rstrip() in Python?
Ava W
ava w profile pic

In Python, bothstrip() andrstrip() are string methods used to remove characters from the beginning and end of a string. However, there is a difference in their behavior. Here's a detailed explanation of the differences betweenstrip() andrstrip(): strip(): Thestrip() method removes characters from both ends (beginning and end) of a string. By default, it removes leading and trailing whitespace characters (spaces, tabs, newlines) from the string.

1
2
3
4
5
6

my_string = "  Hello World  "

stripped_string = my_string.strip()

print(stripped_string)  # Output: "Hello World"

In this example,my_string.strip() removes the leading and trailing whitespace characters from the stringmy_string, resulting in"Hello World". You can also provide a specific set of characters tostrip() as an argument. It removes any leading or trailing occurrences of those characters.

1
2
3
4
5
6

my_string = "***Hello World***"

stripped_string = my_string.strip("*")

print(stripped_string)  # Output: "Hello World"

In this case,my_string.strip("*") removes the leading and trailing asterisks from the string, resulting in"Hello World". rstrip(): Therstrip() method removes characters only from the right (end) side of a string. By default, it removes trailing whitespace characters.

1
2
3
4
5
6

my_string = "  Hello World  "

stripped_string = my_string.rstrip()

print(stripped_string)  # Output: "  Hello World"

In this example,my_string.rstrip() removes the trailing whitespace characters from the stringmy_string, leaving the leading whitespace intact. Similar tostrip(), you can provide a specific set of characters torstrip() to remove trailing occurrences of those characters.

1
2
3
4
5
6

my_string = "***Hello World***"

stripped_string = my_string.rstrip("*")

print(stripped_string)  # Output: "***Hello World"

In this case,my_string.rstrip("*") removes the trailing asterisks from the string, resulting in"*Hello World". To summarize, the main difference betweenstrip() andrstrip() is thatstrip() removes characters from both ends of the string, whilerstrip() removes characters only from the right (end) side. By default, both methods remove whitespace characters, but you can provide a specific set of characters to remove as well. Choose the appropriate method based on your specific requirements and the desired outcome for manipulating strings in Python.