Replace strings in a list (using re.sub)

后端 未结 5 573
萌比男神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 08:59

    Your loop is actually perfectly fine! There are two other issues.

    1. You're setting file_lst_trimmed equal to your string every iteration of the loop. You want to use append as in file_lst_trimmed.append("apple").

    2. Your regular expression is '1.fa' when it should really just be '.fa' (assuming you only want to strip .fa extensions).

    EDIT: I now see that you also want to remove the last number. In that case, you'll want '\d+\.fa' (\d is a stand-in for any digit 0-9, and \d+ means a string of digits of any length -- so this will remove 10, 11, 13254, etc. The \ before the . is because . is a special character that needs to be escaped.) If you want to remove arbitrary file extensions, you'll want to put \w+ instead of fa -- a string of letters of any length. You might want to check out the documentation for regex.

提交回复
热议问题