Search code examples
pythonstringfindsubstring

Removing a File Extention from a String in Python (Reverse Indexing)


In a recent project I had to remove the '.txt' extention in a string. I tried using the .find() function as well as .index() and .search() in many ways but nothing came out of it. So, I wrote the following:

file_name = 'myFile.txt is a file'
new_name = file_name[:(len(file_name) - len(file_name.split('.')[len(file_name.split('.')) - 1]) - 1)]

print(new_name)

Output

myFile

It worked fine.

However I was wondering if there was something simpler and cleaner that I could do with reverse indexing... Something that could work not only with extentions but in other similar cases as well. For some reason I couldn't find something that works efficiently in other posts.
Any help would be highly appreciated : )


Solution

  • You can simply use Regex to seach for the text preceeding the . character:

    import re
    
    file_name = 'myFile.txt is a file'
    
    new_name = re.findall(r'(\w+)\.', file_name)[0]
    
    print(new_name)