I'm python beginner.I wrote this code but it can't work successfully.Someone can understand why?
if __name__ == '__main__': # if "pro" begin with "test", delete "test" from "pro". pro = "001001111010010101001" test = "0010" if pro.startswith(test): pro = pro.lstrip(test) # My ideal -> pro == "01111010010101001" print pro print proThis code doesn't output anything.
4 Answers4
str.lstrip() removesall characters that appear in theset of characters you gave it. Since you gave it both0 and1 in that set, and the string consists ofonly zeros and ones, you removed the whole string.
In other words,str.lstrip() doesnot remove a prefix. It removes one character at a time, provided that character is named in the argument:
>>> '0123'.lstrip('0')'123'>>> '0123'.lstrip('10')'23'>>> '0123'.lstrip('20')'123'Remove the firstlen(test) characters instead:
pro = pro[len(test):]1 Comment
lstrip(chars) returns a copy of the string in which all chars have been stripped from the beginning of the string. so if you passtest that contain 1,0 it remove all the characters frompro (pro contain only 0,1) .
>>> pro = pro.lstrip('10')>>> pro''instead you can Just use slicing :
>>> if pro.startswith(test):... pro=pro[len(test):]... >>> pro'01111010010101001'Comments
This is because lstrip removes all of the left characters from the set given so removes everything:
I think that you need:
pro = pro.startswith(test) and pro[len(test):] or prothis will removetest from the start ofpro if it is there.
1 Comment
pro[len(test):] if pro.startswith(test) else pro.Just as extra.. This will also work:
>>> pro = "001001111010010101001">>> test = "0010">>> if pro.startswith(test): pro = pro.partition(test)[-1] print pro011110100101010011 Comment
pro = pro[len(test):] might be more clear than usingpro.partition().Explore related questions
See similar questions with these tags.



