为什么我得到这些不同的输出?

时间:2019-11-13 15:41:30

标签: python string

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

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

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

在这里,对于最后两个打印语句,我希望将输出作为第一个打印语句,因为它已经剥离了“ xyxxyy”,但是在最后两个打印语句中,它的剥离方式与在第一。请告诉我为什么会这样吗?

5 个答案:

答案 0 :(得分:2)

在Python中,由于.lstrip(),删除了包含xyy的字符串中的前导字符。例如:

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

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

print(x)

输出将是:香蕉

答案 1 :(得分:1)

string.lstrip(chars)从字符串的左侧开始删除字符,直到到达chars中未出现的字符为止。

在第二个和第三个示例中,字符串的第一个字符未出现在chars中,因此不会从字符串中删除任何字符。

答案 2 :(得分:0)

我认为是因为char的顺序无关紧要。

xyyyxx将导致相同的结果。它将从左侧删除字符,直到看到不包含的字符。例如:

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

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

实际上,如果仅使用2个字符“ xy”或“ yx”,则会得到相同的结果:

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

在其他情况下,不包括第一个左字符,因此不会剥离

答案 3 :(得分:0)

我只是知道lstrip()被删除,所有作为参数传递的字符的组合都被从左侧删除。

答案 4 :(得分:0)

lstring使用字符串中的字符集,然后从左侧开始删除主字符串中的所有字符

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