1

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?

1
  • 1
    That's python, not pyth. Please be careful about the tags. Also, Python is sensitive to indent, which makes your code incorrect.
    – Amadan
    Commented Sep 17, 2019 at 10:22

1 Answer 1

2

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):]
2
  • i've tried but str object has no attribute startwith, is it necessary to import a module for it to work? Your explanation put me on the right track, I wasn't using the strip function well but so I could find help on the site Commented Sep 17, 2019 at 19:57
  • 1
    str object definitely has startswith attribute, but not startwith attribute. Note the extra "s" in @Amadan code vs comment.
    – bfris
    Commented Sep 17, 2019 at 20:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.