user9121250
user9121250

Reputation:

Why I am getting these different outputs?

print('xyxxyyzxxy'.lstrip('xyy'))
# output:zxxy

print("xyxefgooeeee".lstrip("efg"))
# ouput:xyxefgooeeee

print('reeeefooeeee'.lstrip('eeee'))
# output:reeeefooeeee

Here for the last two print statements, I am expecting output as a first print statement, as it has stripped 'xyxxyy', but in the last two print statements, it is not stripping in the same way as it has done in first. Please tell me why it so?

Upvotes: 0

Views: 643

Answers (5)

misha
misha

Reputation: 122

lstring using the set of the chars in the string and then removes the all characters from the primary string start from the left

print('xyxefgooeeee'.lstrip('yxefg')) 
"""In 'xyxefgooeeee' the first char is 'x' and it exists in the 'yxefg' so 
will be removed and then it will move to the next char 'y','x','x','e','f', 
'g' and then 'o' which doesn't exist. therefore will return string after 'o'
"""
OutPut : ooeeee

print('xyxefgooeeee'.lstrip('efg'))
"""In the xyxefgooeeee' the first char 'x' does to exist in the 'efg' so will
not be removed and will not move to the next char and will return the
entire primary string
"""
OutPut: xyxefgooeeee

Upvotes: 0

see-king_of_knowledge
see-king_of_knowledge

Reputation: 523

I think because the order of char doesn't matter.

xyy or yxx will result in the same thing. It will remove chars from the left side until it sees a char that is not included. For example:

print('xyxxyyzxxy'.lstrip('xyy'))
zxxy

print('xyxxyyzxxy'.lstrip('yxx'))
zxxy

In fact, if you only used 2 chars 'xy' or 'yx' you will get the same thing:

print('xyxxyyzxxy'.lstrip('xy'))
zxxy

In the other cases, the first left char is not included, therefore there's no stripping

Upvotes: 0

user9121250
user9121250

Reputation:

I just got to know lstrip() removes, all combinations of the characters passed as an argument are removed from the left-hand side.

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 60944

string.lstrip(chars) removes characters from the left size of the string until it reached a character that does not appear in chars.

In your second and third examples, the first character of the string does not appear in chars, so no characters are removed from the string.

Upvotes: 1

BlackoutDev
BlackoutDev

Reputation: 107

In Python leading characters in Strings containing xyy are removed because of .lstrip(). For example:

txt = ",,,,,ssaaww.....banana"

x = txt.lstrip(",.asw")

print(x)

The output will be: banana

Upvotes: 2

Related Questions