Python Forum
Python: if 'X' in 'Y' but with two similar strings as 'X'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python: if 'X' in 'Y' but with two similar strings as 'X'
#7
(Feb-01-2019, 09:47 AM)DreamingInsanity Wrote: he only part that wasnt included in the code was that once it found what ending the url had, it would call a function and it would download the file from that url. I needed the ending so I could save it with that specific ending.

That's great example that one should be clear what ultimate goal is.
Instead of checking extensions one by one, you should use proper tools to extract file extension from url

import os
import pathlib

url1 = 'https://www.somedomain.com?download=somefile.div'
url2 = 'https://www.somedomain.com/somefile.divf'

#using os.path.splitext
for url in (url1, url2):
    ext = os.path.splitext(url)[-1]
    local_path = f'c:/somefolder/localfile{ext}'
    print(f'{url} --> {local_path}')
    
print()
# using pathlib
for url in (url1, url2):
    ext = pathlib.Path(url).suffix
    local_path = f'c:/somefolder/localfile{ext}'
    print(f'{url} --> {local_path}')
Output:
https://www.somedomain.com?download=somefile.div --> c:/somefolder/localfile.div https://www.somedomain.com/somefile.divf --> c:/somefolder/localfile.divf https://www.somedomain.com?download=somefile.div --> c:/somefolder/localfile.div https://www.somedomain.com/somefile.divf --> c:/somefolder/localfile.divf >>>
EDIT: I just realised that you may have a case when it url does not end in desired extension.
In this case you may want to check that extension is in predefined list of "eligible" extemsions.
Also instead of using os and pathlib module you can split url string at '.', take the last element and check if it is in the desired list of extensions.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Python: if 'X' in 'Y' but with two similar strings as 'X' - by buran - Feb-01-2019, 01:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to understand strings and lists of strings Konstantin23 2 836 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,833 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Sum similar items tester_V 3 2,022 Jun-29-2021, 06:58 AM
Last Post: tester_V
  Finding multiple strings between the two same strings Slither 1 2,565 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  Splitting strings in python? NLittle17 3 2,437 Jan-05-2019, 09:20 AM
Last Post: Axel_Erfurt
  Similar to Poker bluekade5050 1 35,761 Nov-14-2018, 04:46 PM
Last Post: j.crater
  lists, strings, and byte strings Skaperen 2 4,279 Mar-02-2018, 02:12 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020