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.