我有一个变量:
kid.image_url
存储了一个网址:
/media/pics/byson.jpg
我想删除/ media以便它只包含:
/pics/byson.jpg
我刚开始学习django。任何帮助将不胜感激:)
答案 0 :(得分:3)
stripped = '/media/pics/byson.jpg'.split('/')[2:]
kid.image_url = '/'+'/'.join(stripped)
答案 1 :(得分:0)
考虑使用python os.path.split(path)和os.path.join函数。它们适用于Windows和Linux。这样你的代码就是可移植的。见Splitting a Path into All of Its Parts。以下是工作代码
import os, sys
def splitall(path):
allparts = []
while 1:
parts = os.path.split(path)
if parts[0] == path: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == path: # sentinel for relative paths
allparts.insert(0, parts[1])
break
else:
path = parts[0]
allparts.insert(0, parts[1])
return allparts
image_url = "/media/pics/byson.jpg"
image_url = os.path.join(*splitall(image_url)[2:])