1

我在把这个逻辑写在纸上时遇到了一些麻烦:

我想解析的字符串:"Jan - 2012 Presentation v1.3.ppt.pdf - 500KB" 这个字符串可以变化,但结构总是“NAME+EXT+FILESIZE”

我想退回扩展名。但是由于显而易见的原因,我不能只是split(".") 所以我想出了别的东西:

stringy = "Jan - 2012 Presentation v1.3.ppt.pdf - 500KB"
ext = [".pdf",".jpg",".ppt",".txt",".doc"]

for i in ext:
    indx = stringy.find(i)
    ...

我被困在我需要弄清楚如何告诉 Python 从产生的最大索引开始进行扩展的地方。应该是这样的whatiwant = stringy[indx:4],但我不知道如何告诉它只采用最大的索引......最大的索引显然意味着字符串中的最后一个扩展名,这是我想要得到的那个。在这个特定的例子中,我不关心“ppt”,而是关心“pdf”。

这也许可以以更蟒蛇的方式完成吗?或者至少更有效?

4

3 回答 3

2
In [44]: stringy[stringy.rfind('.'):stringy.rfind('.')+4]
Out[44]: '.pdf'
于 2012-11-02T11:46:28.490 回答
1

使用regex

>>> strs="Jan - 2012 Presentation v1.3.ppt.pdf - 500KB"

>>> re.findall(r"(\.\w+)",strs)[-1]
'.pdf'

或者:

>>> re.findall(r".*(\.\w+)",strs)
['.pdf']
于 2012-11-02T11:43:30.777 回答
0

试试这个:

>>> stringy = "Jan - 2012 Presentation v1.3.ppt.pdf - 500KB"
>>> extension = stringy.split(".")[-1].split("-")[0].strip()
>>> extension
'pdf'
于 2012-11-02T11:43:56.420 回答