So my question is – I have a code like that:
test_text = "lorem ipsum dolor sit amet"
for each in test_text:
#do some stuff
And while it surely works for the letter that’s currently “highlighted” by for, I can’t do anything to the previous ones without having an additional variable that I would increment in each iteration so that I could address test_text[said_variable]. I mean – let’s say that for every letter user wants, I have to print the letter that’s five index places before the said letter – without the additional variable, I can’t do this. Could someone please help? Can I address something prior (or after) to what for is now working on without having to play like that?
I’m sorry for the newbish question, but I’m just starting in Python and couldn’t find anything on the matter.
I don’t believe you can do this without a second variable, but you don’t have to manually increment it:
enumerate docs
Note that a negative list index will go to the end of the list, i.e.
test_text[-1]will return the last character, so you’d have to add a check oni-5if you don’t want this behavior.