Search code examples
pythonstringpython-3.xstrip

Keeping track of number of characters removed in strings, python `strip()`


I have a pair of strings. In this case, let's think of them as two separate strings assigned to unique variables. These strings have equal length:

var1 = 'AnAppleADayKeepsTheDoctorAway'
var2 = '000Ig00000noranceIsBliss00000'

The most efficient way I know to strip beginning and trailing characters from a string in Python is the method strip():

print(var2.strip('0'))
'Ig00000noranceIsBliss'

I would like to remove the same number of character from the string var1, as they are a "pair". In this case, that would be remove the first three characters and the trailing five characters, i.e.

'ppleADayKeepsTheDocto'

Is there a method which allows me to efficiently strip characters like in var1 and then keep track of the number of these characters to do the same for the second string,var2? I'm not sure strip() would be the best method for this task.

EDIT: Obviously, there's a solution.

e.g.

length_original = len(var2)
num_left_chars = len(var2) - len(var2.lstrip('0'))
num_right_chars = len(var2.rstrip('0'))
edited = var1[num_left_chars:num_right_chars]
print(edited)
## printed
## 'ppleADayKeepsTheDocto'

I'm looking for an efficient solution. If there a quicker Pythonic method?


Solution

  • I would do it in two steps: first, strip the front, and then strip the back. Then you can count how many characters were stripped on each side, and use string slicing. You can use lstrip() and rstrip() for this. Example:

    var1 = 'AnAppleADayKeepsTheDoctorAway'
    var2 = '000Ig00000noranceIsBliss00000'
    
    num_leading = len(var2) - len(var2.lstrip('0'))
    num_trailing = len(var2) - len(var2.rstrip('0'))
    
    print(var2.strip())
    print(var1[num_leading:-1*num_trailing])