I want to remove from my list every \n that is before the element 'Ecrire'. It work just for the first case and not the other cases, And I really don't understand why Here is my code :
Corps2 = ['Debut', '\n', '\n', 'Note', ' ', '<-', ' ', 'Saisie()', ' ', '', '\n', '\n', 'Selon que\n', ' ', 'Note', ' ', '≥', ' ', '16', ' ', '', ' ', '', ' ', ':', ' ', '', '\n', '\n', 'Ecrire', ' ', "('TB')", '\n', '\n', '', ' ', 'Note', ' ', '≥', ' ', '14', ' ', '', ' ', '', ' ', ':', ' ', '', '\n', '\n', 'Ecrire', ' ', "('B')", '\n', '\n', '', ' ', 'Note', ' ', '≥', ' ', '12', ' ', '', ' ', '', ' ', ':', ' ', '', '\n', '\n', 'Ecrire', ' ', "('AB')", '\n', '\n', '', ' ', 'Note', ' ', '≥', ' ', '10', ' ', '', ' ', '', ' ', ':', ' ', '', '\n', '\n', 'Ecrire', ' ', "('Passable')", '\n', '\n', 'Sinon', ' ', ':', ' ', 'Ecrire', ' ', "('Redoublant')", '\n', '\n', 'Fin_Si']
for i in Corps2:
if i =='Ecrire' and Corps2[Corps2.index('Ecrire')-2 :Corps2.index('Ecrire')]==['\n','\n'] :
del Corps2[Corps2.index('Ecrire')-2 :Corps2.index('Ecrire')]
The index
call will always return the first instance of the string. This is one of those situations where yor really want to loop over the indices of the list rather than directly loop over its elements.
Notice also that you can't del
elements from the list you are currently traversing; but of course, when you loop over an indirect index, you can, as long as you termrnate on any IndexError
.
for idx in range(len(Corps2)-1):
try:
if Corps2[idx] == '\n' and Corps2[idx+1] == 'Ecrire:
del Corps2[idx]
except IndexError:
break
Demo: https://ideone.com/LhEvUB
You should understand how the IndexError
could happen - you are shortening the list for each deleted element, and so the calculated ending index will overshoot the list's end by that many items. Also, by lucky coincidence, we already know that the element which replaces the '\n'
will never also be '\n'
(namely, because it will be 'Ecrire'
) so we can conveniently avoid the required complications if this were not the case.
Tangentially, you should conventionally not capitalize the names of regular variables in Python; capitalized names are usually class names.