1

I have this code below trying to remove the leading characters of a string by using an indicator to where to stop the trim.

I just want to know if there are some better ways to do this.

#Get user's input: file_name
file_name = str.casefold(input("Filename: ")).strip()

#Get the index of "." from the right of the string
i = file_name.rfind(".")

# getting the file extension from the index i
ext = file_name[i+1:]

# Concatinating "image/" with the extractted file extension
new_fname = "image/" + ext
print(new_fname)

1 Answers1

1

Looking at your code you can shorten it to:

file_name = input("Filename: ")
new_fname = f"image/{file_name.rsplit('.', maxsplit=1)[-1]}"

print(new_fname)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Hi, yes this is the one I want to do. I just did my step by step to get into the correct procedure but I realized it is too long. Anyhow, just want to know the meaning of the [-1] at the end of your fstring syntax. – SoulSeeker916 Sep 23 '22 at 20:07
  • @SoulSeeker916 `[-1]` will get the [last element](https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list) of the list. – Andrej Kesely Sep 23 '22 at 20:08