I have an app that will show images from reddit. Some images come like this https://i.stack.imgur.com/LKuXA.jpg, when I need to make them look like this https://i.stack.imgur.com/yfiH1.jpg. Just add an (i) at the beginning and (.jpg) at the end.
            Asked
            
        
        
            Active
            
        
            Viewed 322 times
        
    3 Answers
3
            
            
        You can use a string replace:
s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
This sets s to:
'http://i.imgur.com/Cuv9oau.jpg'
 
    
    
        jh314
        
- 27,144
- 16
- 62
- 82
2
            This function should do what you need. I expanded on @jh314's response and made the code a little less compact and checked that the url started with http://imgur.com as that code would cause issues with other URLs, like the google search I included. It also only replaces the first instance, which could causes issues.
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)
Gives:
>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur
- 
                    Thanks every one, I ended up using this version. Sometimes I still get page load errors because there is no image, I click on the url and it says page not found or something different. Is there a way to add a check for the image and if its not found, than skip it – gallly Jul 11 '13 at 03:53
- 
                    That URL has an extra `/` at the end, so it is an invalid URL. You can check the URL is valid during transformation, but you'd be better the ask a new question for that. – Jul 11 '13 at 03:58
- 
                    thanks I added code to remove it and so far its been working! – gallly Jul 11 '13 at 04:05
1
            
            
        You should use Python's regular expressions to place the i.  As for the .jpg you can just append it.
 
     
    