Does strip() only work for single character arguments?

Question

In the context of this exercise, does strip() only work for single character arguments?

Answer

No, you can apply strip() with an empty string argument, or with strings that are longer than a single character.

When applying strip() with a string argument longer than a single character, it will also remove overlapping sequences of characters.

For example,

string = "aaabaaa"
new_string = string.strip("aa")

print(new_string) # b
5 Likes

This explanation is not correct. It won’t remove “overlapping sequences”, it treats each character seperately.

string = "aba"
new_string = string.strip("aa")

print(new_string) # b

string = "abxba"
new_string = string.strip("ab")

print(new_string) # x
6 Likes

I wanted to expand on this a bit more. strip() removes characters only from the start and end of a string. If you give it multiple strings it will treat each character separately. If it sees an instance of that character at the start or end it will keep removing it until it it finds a character that wasn’t part of the argument.

writing

string.strip("ab")

is the same as writing:

string.strip("a")
string.strip("b")

The examples might clarify concepts further

my_string = "aaaxBTSa1axa"
new_string1 = my_string.strip("a") 

print(new_string1) # xBTSa1ax

new_string2 = my_string.strip("aaaaaaaa") 
print(new_string2) # xBTSa1ax
# strip("a") strip("aa") strip("aaaaaaaaa") will all give the same result.
# there is no point in repeating a character since they are all treated as separate characters to remove

new_string3 = my_string.strip("x")
print(new_string3) # aaaxBTSa1axa
# remains the same because 'x' is not at the start or end

new_string4 = my_string.strip("ax")
print(new_string4) #BTSa1
# keeps removing all "a"s and "x"s ONLY IF they are the start or end of my_string
9 Likes