1

Below this is my code, I have a tuple of different possible extensions that the user can use to open a file. But the files that the user will open will have a name (like cat.zip or daughter.jpg). I want to remove this name (cat in the first one, daughter in the second) and replace it with "image/" followed by whatever extension they used. I would greatly appreciate it if you could help by explaining me how to figure this out.

P.S: The code may look unfinished, that's because it is. I'm trying to figure this out before continuing.

def main():
    ext = (".gif", ".jpeg", ".jpg", ".png", ".pdf", ".txt", ".zip")
    file = input("What file would you like to run? \n>> ")
    if file.endswith(ext):
        print(file.lstrip(ext))

main()

I tried using the .replace() function or .lstrip, but I couldn't figure out how to only limit the .replace function to only the text before the extension, if I use specific characters, it could mess up the extensions being printed. I am unable to use the .lstrip function with a tuple from my experience.

5 Answers 5

5

There are multiple ways to do this, but the simplest way is probably to use rsplit.

filename = "somefile.gif"
basename, ext = filename.rsplit(".", maxsplit=1)
replacement = "image/" + ext
Sign up to request clarification or add additional context in comments.

Comments

3

you can use the split function in python for the strings to get the extension, the split function is a property of standard strings in python which takes an argument as the separator and divides the string into parts. In your case extensions are signed via a ., so you can divide the string into several parts and take the last one.

So the code should be,

def main():
    ext = ["gif", "jpeg", "jpg", "png", "pdf", "txt", "zip"]
    file = input("What file would you like to run? \n>> ")
    extension = file.split('.')[-1] # here split returns a list of divisions, the extension is the very last part of that list
    if extension in ext:
        print("images/" + extension)
    else:
        print("File extension not valid.")

main()

I am not sure what you mean by adding images/ with the extension but however you can now edit the code suitable to your program

Comments

1

For your specific case, you mentioned you only want to replace the start of the file. In this case, try:

def main():
    ext = (".gif", ".jpeg", ".jpg", ".png", ".pdf", ".txt", ".zip")
    file = input("What file would you like to run? \n>> ")
    for possible_end in ext:
        if file.endswith(possible_end):
            print("image" + possible_end)

main()

You need to loop through all the possible endings in the tuple, not just provide the tuple itself. This'll print 'image' + the appropriate file end. Otherwise, it won't print anything.

Comments

1

you could work with a sed style regular expression...

's|^.*\.([a-z]{3,4})$|image/\1|'

eg, in bash...

echo '
something.jpg
thingy.png
junk.tiff
' | sed -E 's|^.*\.([a-z]{3,4})$|image/\1|'

image/jpg
image/png
image/tiff

This captures and saves the extension with (\.[a-z]{3,4}$) (ie, whatever text is at the end of the string that has a dot followed by 3 or 4 lower case letters) then pastes the captured text (with \1) to the end of the string 'image', replacing the original basename (minus extension), which is matched by ^.*. This expression can be made case insensitive if required.

If accepted extensions need to be limited:

echo '
something.jpg
thingy.png
junk.tiff
' | sed -E 's:^.*\.(jpg|png|tiff)$:image/\1:'

image/jpg
image/png
image/tiff

This syntax (or similar) likely works in some python library like re.

[Edited to replace dot with slash...]

Comments

0

Using a regular expression you can both validate and isolate the components of the input string that you're interested in as follows:

import re

def main() -> str:
    ex = r"^(.+)\.(gif|jpeg|jpg|png|pdf|txt|zip)$"
    file = input("What file would you like to run? ")
    return f"image/{m.group(1)}" if (m := re.match(ex, file)) else ""

print(main())

Example:

What file would you like to run? abc.gif
image/abc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.