1

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 pro

This code doesn't output anything.

Martijn Pieters's user avatar
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
askedJan 1, 2015 at 14:02
Misato Morino's user avatar
0

4 Answers4

8

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):]
answeredJan 1, 2015 at 14:04
Martijn Pieters's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much everyone!! I could do it as my ideal.
2

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'
answeredJan 1, 2015 at 14:04
Kasravnd's user avatar

Comments

1

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 pro

this will removetest from the start ofpro if it is there.

answeredJan 1, 2015 at 14:10
Steve Barnes's user avatar

1 Comment

If you are going to make it a one-liner then at least use a conditional expression:pro[len(test):] if pro.startswith(test) else pro.
1

Just as extra.. This will also work:

>>> pro = "001001111010010101001">>> test = "0010">>> if pro.startswith(test):       pro = pro.partition(test)[-1]       print pro01111010010101001
answeredJan 1, 2015 at 14:26
Shahriar's user avatar

1 Comment

I thinkpro = pro[len(test):] might be more clear than usingpro.partition().

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.