Replace strings in a list (using re.sub)

后端 未结 5 574
萌比男神i
萌比男神i 2020-12-06 08:30

I am trying to replace parts of file extensions in a list of files. I would like to be able to loop through items (files), and remove the extensions. I don\'t know how to ap

5条回答
  •  广开言路
    2020-12-06 09:11

    No need for regex, use the standard library os and os.path.splittext for this.

    Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').

    import os.path
    
    l = ['hello.fa', 'images/hello.png']
    
    [os.path.splitext(filename)[0] for filename in l]
    

    Returns

    ['hello', 'images/hello']
    

提交回复
热议问题