Replace strings in a list (using re.sub)

后端 未结 5 569
萌比男神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:06

    You can try this:

    import re
    file_lst = ['cats1.fa', 'cats2.fa', 'dog1.fa', 'dog2.fa']
    final_list = [re.sub('\d+\.\w+$', '', i) for i in file_lst]
    

    Output:

    ['cats', 'cats', 'dog', 'dog']
    

提交回复
热议问题