Search code examples
pythonstrip

The strip command works "too much" it even erases what is not supposed to be erased


I'm trying to use the.strip() function to remove a part of the text in several variables.

Here is my code :

image_list = [] # on créer un tableau dans lequel on va mettre toutes les images 
for filename in glob.glob(chemin+"\*.jpg" ): # I browse all.jpg files that are in the directory indicated by the variable "chemin".
   im=Image.open(filename)
   image_list.append(im) # I add the image to a table
   print("\n",filename, "\n", chemin,"\n", filename.strip(chemin),"\n\n") # Here is the test I do to see the different texts and the text where I use the strip function

And this is what I get :

D:\Prog&Job\Ebay\Produit\Beyblade\toupie + boitier_bleu\images secondaire\boitier_8.JPG

D:\Prog&Job\Ebay\Produit\Beyblade\toupie + boitier_bleu\images secondaire

8.JPG

First there is the file name and path, then the directory name and then the path, and when I try to strip the file to remove all the path, it removes the beginning (here: D:\Prog&Job\Ebay\Produit\Beyblade\toupie + boitier_bleu\images secondaire ), but it also removes "boitier_"

Do you know why? Thank you in advance

EDIT : Here is the solution I wanted :

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> print os.path.relpath(full_path, '/book/html')
'wa/foo/bar'

it's an example from this : How to remove a path prefix in python?


Solution

  • strip does not remove a certain substring found as prefix/suffix. It removes any characters found in the string passed to it that are at the start or end of the string. Note:

    "TESTED SETS".strip("TES") # => "D " (T, E and S removed from front and back)
    

    You can remove a prefix substring in any number of ways. This is one:

    if string.startswith(prefix):
        string = string[len(prefix):]