Exercise 23
Write a Python program that prompts the user to enter a file name, and then returns the extension of the file. Example if the user enters coursPython.pdf the program returns the message "The file extension is .pdf".
Solution
filename = input("Enter a filename: ") extension = filename.split(".")[-1] print("The file extension is ." + extension) """ Example usage: Enter a filename: coursPython.pdf The file extension is .pdf """
Note
Explanation:
- We use the input() function: in order to prompts the user to enter a filename.
- Then, the split() function: is used to separate the filename into a list of strings using the period (.) as the separator.
- The [-1] index: is used to retrieve the last item in the list, which is the file extension.
- Finally: the file extension is printed to the screen using the print() function.
This program assumes that the user will enter a valid file name with an extension. If the user enters a file name without an extension or with multiple periods, the program may not work as intended.
Younes Derfoufi
my-courses.net
[…] Exercise 23 * || Solution […]