Home > Mobile >  i tried case statement in python but every time i run i got my default as a result
i tried case statement in python but every time i run i got my default as a result

Time:08-30

Exten=input("Filename:")
match Exten:
    case "Gif":
        print("image/gif")
    case "jeg":
        print("image/jpeg")
    case "jpeg":
        print("image/jpeg")
    case "png":
        print("image/png")
    case "pdf":
        print("application/pdf")
    case "txt":
        print("text/plain")
    case "zip":
        print("application/zip")
    case default:
        print("application/octet-stream")

whatever file name I got only output is default, please explain where did I miss

CodePudding user response:

Maybe you should split to get the extension. I think you get the whole name of the file and it does not match.

fileName=input("Filename with extension:") 
Exten = data.split(".")    
match Exten: 
    case ‘Gif‘: print("image/gif") 
    case ‘jeg‘: print("image/jpeg") 
    case ‘jpeg‘: print("image/jpeg") 
    case ‘png‘: print("image/png") 
    case ‘pdf‘: print("application/pdf") 
    case ‘txt‘: print("text/plain") 
    case ‘zip‘: print("application/zip") 
    case default: print("application/octet-stream")

CodePudding user response:

If Exten is a filename, you need to match on the suffix, not the entire filename. You can use split() for this. Split the string at the period which will create a list with 2 items, the filename and the suffix. You just need to add a line to split and change the match to only use the second item of the list.

Exten=input("Filename:")
exten_split = Exten.split(".")
match exten_split[1]:

You can find examples of this at https://www.w3schools.com/python/ref_string_split.asp

  • Related