1

I am learning python and I made a basic program where the user takes the link of a photo and inputs it, then the program downloads that photo. In order to make sure that the user doesn't enter a link that is a webpage instead of a photo, I had the program check what the file extension was by using string slicing, but I can't seem to find out how to slice the string backwards

I know that this is an dumb question but after an hour of searching I still can't find the answer. Here is the code

import random
import urllib.request
import urllib.parse

def download_web_image(url, file_format):
    try:
        name = random.randrange(1, 1000)
        full_name = str(name) + file_format
        urllib.request.urlretrieve(url, full_name)
        print("Image download successful!")
        print("Image named " + full_name)
    except:
        print('Error')


def get_user_url():
    url = input("Now enter the url of the photo you want to download:")
    try:

        if url[0:3:-1] is '.png':
            download_web_image(url, ".png")
        elif url[0:4:-1] is 'gepj.':
            download_web_image(url, '.jpeg')
        elif url[0:3:-1] is '.gpj':
            download_web_image(url, '.jpg')
        else:
            print('the file format is uncompatible: ' + url[1:4:-1])

    except:
        print('The url is not valid!')

print('look for an image on a website, make sure it is a JPG or PNG file or it will not work!')
get_user_url()

Thank you for the help. and no, I do not want the string to show up backwards.

Doozku
  • 41
  • 5
  • Instead of looking at the file extension (which could be misleading, or not exist), it would get better to fetch the page (or at least look at the headers, via HTTP HEAD). `Content-type` is the one you should be looking at. – Jim Garrison Jul 16 '15 at 02:48
  • See also the `endswith` method on python's strings: `"filename.png".endswith(".png")` – Jim Garrison Jul 16 '15 at 02:49
  • 1
    related: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation (Yes, I know it's tagged list, but strings are the same) – NightShadeQueen Jul 16 '15 at 02:49
  • 2
    If you want to check the extension, `os.path.splitext` is probably what you're looking for. – Kyle G Jul 16 '15 at 02:51

3 Answers3

5

I suggest you use the built-in method endswith saves the trouble of variable size extensions(png,jpeg,jpg...etc), this way:

>>>url = 'https://www.python.org/static/community_logos/python-logo-master-v3-TM.png'
>>>url.endswith('.png')
True
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
1

What you want is to index by negative numbers, which search from the end of the list/string:

extension = url[-3:] will retrieve the last 3 characters in url.

url[-1] is the last character of url, url[-2] is the 2nd-to-last, and so on. So url[-3:] gets everything from the 3rd-to-last character to the end of the string.

iobender
  • 3,346
  • 1
  • 17
  • 21
0

The following type of approach might be easier to follow:

def get_user_url():
    url = input("Now enter the url of the photo you want to download: ")

    try:
        extension = os.path.splitext(url.lower())[1]

        if extension in [".png", ".jpeg", ".jpg"]:
            download_web_image(url, extension)
        else:
            print('the file format is uncompatible: {:}'.format(extension))

    except:
        print('The url is not valid!')

I suggest you also convert your input into lowercase so that you can catch ".JPG" at the same time.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97