Newbie asks, how to get rid of the last four characters of a string?

Skip Montanaro skip at pobox.com
Wed Jan 22 09:48:02 EST 2003


    Christopher> I know I can do this with regular expressions, but is there
    Christopher> a function that can be used to chomp off the last four
    Christopher> characters without having to import the re module?

Sure:

    >>> fn = "something.doc"
    >>> fn[-4:]
    '.doc'
    >>> fn[:-4]
    'something'

or filename-like and less reliant on the fact that your extension contains
precisely four characters:

    >>> os.path.split(fn)
    ('', 'something.doc')
    >>> os.path.splitext(fn)
    ('something', '.doc')

Skip





More information about the Python-list mailing list