Search code examples
pythonpython-3.xstrip

strip() function doesn't remove trailing numbers


I try the following code but fails to remove the trailing digits using python 3.4.3

file_name = "48athens22.jpg"
result = file_name.strip("0123456789")
print (result)

Output: athens22.jpg

What has gone wrong?


Solution

  • strip() only strips from the end of a string; the 22 is not at the end of the string.

    Here's how to do what you want:

    import os
    
    
    def strip_filename(filename):
        root, ext = os.path.splitext(filename)
        root = root.strip('0123456789')
        return root + ext
    
    
    print(strip_filename('48athens22.jpg'))  # athens.jpg