Misato Morino
Misato Morino

Reputation: 75

binary with string in Python

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.

Upvotes: 1

Views: 92

Answers (4)

Kasravnd
Kasravnd

Reputation: 107287

lstrip(chars) returns a copy of the string in which all chars have been stripped from the beginning of the string. so if you pass test that contain 1,0 it remove all the characters from pro (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'

Upvotes: 2

Shahriar
Shahriar

Reputation: 13804

Just as extra.. This will also work:

>>> pro = "001001111010010101001"
>>> test = "0010"
>>> if pro.startswith(test):
       pro = pro.partition(test)[-1]
       print pro

01111010010101001

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28370

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 remove test from the start of pro if it is there.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121544

str.lstrip() removes all characters that appear in the set of characters you gave it. Since you gave it both 0 and 1 in that set, and the string consists of only zeros and ones, you removed the whole string.

In other words, str.lstrip() does not 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 first len(test) characters instead:

pro = pro[len(test):]

Upvotes: 8

Related Questions