如何修改python中随机选取的url

如何修改python中随机选取的url,python,flask,Python,Flask,我有一个应用程序,将显示来自reddit的图像。有些图像是这样的,当我需要让它们看起来像这样的时候。只需在开头添加一个(i),在结尾添加一个(.jpg)。您应该使用来放置i。至于.jpg,您只需。您应该使用来放置i。至于.jpg,您可以使用字符串替换: s = "http://imgur.com/Cuv9oau" s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "") 这将s设置为: 'h

我有一个应用程序,将显示来自reddit的图像。有些图像是这样的,当我需要让它们看起来像这样的时候。只需在开头添加一个(i),在结尾添加一个(.jpg)。

您应该使用来放置
i
。至于
.jpg
,您只需。

您应该使用来放置
i
。至于
.jpg
,您可以使用字符串替换:

s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
这将s设置为:

'http://i.imgur.com/Cuv9oau.jpg'

您可以使用字符串替换:

s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
这将s设置为:

'http://i.imgur.com/Cuv9oau.jpg'

这个函数应该满足您的需要。我对@jh314的响应进行了扩展,使代码稍微不紧凑,并检查url是否以
http://imgur.com
,因为该代码会导致其他URL出现问题,比如我包含的谷歌搜索。它还仅替换第一个实例,这可能会导致问题

def fixImgurLinks(url):
    if url.lower().startswith("http://imgur.com"):
        url = url.replace("http://imgur", "http://i.imgur",1) # Only replace the first instance.
        if not url.endswith(".jpg"):
            url +=".jpg"
    return url

for u in ["http://imgur.com/Cuv9oau","http://www.google.com/search?q=http://imgur"]:
    print fixImgurLinks(u)
给出:

>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur

这个函数应该满足您的需要。我对@jh314的响应进行了扩展,使代码稍微不紧凑,并检查url是否以
http://imgur.com
,因为该代码会导致其他URL出现问题,比如我包含的谷歌搜索。它还仅替换第一个实例,这可能会导致问题

def fixImgurLinks(url):
    if url.lower().startswith("http://imgur.com"):
        url = url.replace("http://imgur", "http://i.imgur",1) # Only replace the first instance.
        if not url.endswith(".jpg"):
            url +=".jpg"
    return url

for u in ["http://imgur.com/Cuv9oau","http://www.google.com/search?q=http://imgur"]:
    print fixImgurLinks(u)
给出:

>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur

谢谢大家,我最终使用了这个版本。有时我仍然会收到页面加载错误,因为没有图像,我单击url,它会显示页面未找到或其他内容。有没有办法为图像添加一个检查,如果没有找到,跳过它该URL在末尾有一个额外的
/
,因此它是一个无效的URL。你可以在转换过程中检查URL是否有效,但是你最好问一个新问题。谢谢,我添加了代码来删除它,到目前为止它一直在工作!谢谢大家,我最终使用了这个版本。有时我仍然会收到页面加载错误,因为没有图像,我单击url,它会显示页面未找到或其他内容。有没有办法为图像添加一个检查,如果没有找到,跳过它该URL在末尾有一个额外的
/
,因此它是一个无效的URL。你可以在转换过程中检查URL是否有效,但是你最好问一个新问题。谢谢,我添加了代码来删除它,到目前为止它一直在工作!