Replace strings in a list (using re.sub)

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

    You can use a list comprehension to construct the new list with the cleaned up files names. \d is the regex to match a single character and $ only matches at the end of the string.

    file_lst_trimmed = [re.sub(r'\d\.fa$', '', file) for file in file_lst]
    

    The results:

    >>> file_lst_trimmed 
    ['cats', 'cats', 'dog', 'dog']
    

提交回复
热议问题