Search code examples
pythonstringsubstring

Replacing a set of characters in a string


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)

Solution

  • 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)