我不确定 TkinterDnD2 库是否会返回单个字符串中的路径流或字符串中的单个路径。
如果它是字符串中的单个路径,则解决方案很简单:
>>> str1="{mypath/to/file}"
>>> str1[1:-1]
输出将是
'mypath/to/file'
但我想你的问题是单个字符串中有多个路径。您可以实现如下代码。
认为 str1 是具有多个路径的字符串:
str1="{mypath1/tofile1}{mypath3/tofile3}{mypath2/tofile2}"
i=0
patharr=[]
while(str1.find('{',i)>=0):
strtIndex=str1.find('{',i)
if(str1.find('}',strtIndex+1)>0):
endIndex=str1.find('}',strtIndex+1)
patharr.append(str1[strtIndex+1:endIndex])
print(str1[strtIndex:endIndex+1])
i=endIndex+1
print(patharr)
现在输出如下:
['mypath1/tofile1', 'mypath3/tofile3', 'mypath2/tofile2']
因此,根据您在下面评论中的问题,文件路径的代码在文件路径中带有花括号。
str1 = "{mypath}}}}1/tofil{{{e1}{mypath3/tofile3}{mypath2/tofile2}}}}}}"
i = 0
patharr = []
while (str1.find('{', i) >= 0):
strtIndexfirst = str1.find('{', i)
notFound = True
strtIndex = strtIndexfirst
while (notFound and strtIndex < len(str1)):
if (str1.find('}', strtIndex + 1) > 0):
findInd = str1.find('}', strtIndex + 1)
if (findInd == len(str1) - 1):
endIndex = str1.find('}', strtIndex + 1)
patharr.append(str1[strtIndexfirst + 1:endIndex])
print(str1[strtIndex:endIndex + 1])
i = endIndex + 1
break
if (str1[findInd + 1] == '{'):
endIndex = str1.find('}', strtIndex + 1)
patharr.append(str1[strtIndexfirst + 1:endIndex])
print(str1[strtIndex:endIndex + 1])
i = endIndex + 1
notFound = False
else:
strtIndex = findInd
else:
strtIndex = str1.find('}', strtIndex + 1)
print(patharr)
对于上面的字符串输出是
['mypath}}}}1/tofil{{{e1', 'mypath3/tofile3', 'mypath2/tofile2}}}}}']
如果str1是
str1="{{{mypath1/tofil}}e1}{mypath3/tofile3}{mypath2/tofile2}}}}}}"
输出是
['{{mypath1/tofil}}e1', 'mypath3/tofile3', 'mypath2/tofile2}}}}}']
也适用于其他测试用例。这段代码运行良好。