Python 查找问题 [英] Python Find Question
问题描述
我正在使用 Python 从使用 rfind 的链接中提取文件名,如下所示:
I am using Python to extract the filename from a link using rfind like below:
url = "http://www.google.com/test.php"
print url[url.rfind("/") +1 : ]
这适用于链接末尾没有/的情况,并返回test.php".我在结尾遇到了与/的链接,例如 "http://www.google.com/test.php/".当末尾有/"时,我无法获取页面名称,有人可以帮忙吗?
This works ok with links without a / at the end of them and returns "test.php". I have encountered links with / at the end like so "http://www.google.com/test.php/". I am have trouble getting the page name when there is a "/" at the end, can anyone help?
干杯
推荐答案
仅删除末尾的斜杠是行不通的,因为您可能有一个如下所示的 URL:
Just removing the slash at the end won't work, as you can probably have a URL that looks like this:
http://www.google.com/test.php?filepath=tests/hey.xml
...在这种情况下,您将返回hey.xml".您可以使用 urlparse 去掉参数,而不是手动检查这个,然后检查其他人建议的:
...in which case you'll get back "hey.xml". Instead of manually checking for this, you can use urlparse to get rid of the parameters, then do the check other people suggested:
from urlparse import urlparse
url = "http://www.google.com/test.php?something=heyharr/sir/a.txt"
f = urlparse(url)[2].rstrip("/")
print f[f.rfind("/")+1:]
这篇关于Python 查找问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!