【问题标题】:The strip command works "too much" it even erases what is not supposed to be erasedstrip 命令工作“太多”,它甚至会擦除不应该​​擦除的内容
【发布时间】:2020-01-18 04:34:01
【问题描述】:

我正在尝试使用 .strip() 函数来删除几个变量中的部分文本。

这是我的代码:

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

这就是我得到的:

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

首先是文件名和路径,然后是目录名,然后是路径,当我尝试剥离文件以删除所有路径时,它会删除开头 (这里: D:\Prog&Job\Ebay\Produit\Beyblade\toupie + boitier_bleu\images secondaire ),但它也删除了“boitier_”

你知道为什么吗? 提前谢谢你

编辑:这是我想要的解决方案:

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

这是一个例子:How to remove a path prefix in python?

【问题讨论】:

  • 那是python,而不是pyth。请注意标签。此外,Python 对缩进很敏感,这会使您的代码不正确。

标签: python strip


【解决方案1】:

strip 不会删除作为前缀/后缀找到的某个子字符串。它会删除在传递给它的字符串中找到的位于字符串开头或结尾的任何字符。注意:

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

您可以通过多种方式删除前缀子字符串。这是一个:

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

【讨论】:

  • 我试过但str对象没有属性startwith,是否需要导入模块才能工作?你的解释让我走上了正轨,我没有很好地使用 strip 功能,但我可以在网站上找到帮助
  • str 对象肯定有startswith 属性,但没有startwith 属性。请注意@Amadan 代码与注释中的额外“s”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2023-02-25
  • 2021-05-24
  • 2014-05-14
相关资源
最近更新 更多