Replacing a set of characters in a string

Question:

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)
Asked By: SoulSeeker916

||

Answers:

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)
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.