简体   繁体   English

如何向后切字符串python

[英]How to slice strings backwards python

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. 我正在学习python,并制作了一个基本程序,用户将照片的链接输入并输入,然后程序下载该照片。 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. 不,我不希望该字符串向后显示。

I suggest you use the built-in method endswith saves the trouble of variable size extensions( png , jpeg , jpg ...etc), this way: 我建议您使用内置方法endswith节省可变大小扩展名( pngjpegjpg ...等)的麻烦,方法是:

>>>url = 'https://www.python.org/static/community_logos/python-logo-master-v3-TM.png'
>>>url.endswith('.png')
True

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 . extension = url[-3:]将检索url的最后3个字符。

url[-1] is the last character of url , url[-2] is the 2nd-to-last, and so on. url[-1]是最后一个字符urlurl[-2]是第二到最后一个,等等。 So url[-3:] gets everything from the 3rd-to-last character to the end of the string. 因此url[-3:]可以获取从倒数第3个字符到字符串末尾的所有内容。

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. 我建议您也将输入转换为小写,以便您可以同时捕获“ .JPG”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM