LeapyNick
LeapyNick

Reputation: 105

How do I access a part of a string by by going backwards in a loop

myList = []
myString = "this is my striNg 7"

Say I wanted to access "N" but I needed to do it by going backwards in a loop like this-

for i in myString:
    if i == "7":
       myList.append(i - 3 spaces)

How do I do this? I am struggling to find answers. Thanks

Edit- Im sorry im new to this and im not sure why it is not formatting this correctly

Upvotes: 2

Views: 59

Answers (3)

lupodellasleppa
lupodellasleppa

Reputation: 127

Not sure I'm getting what you're asking here. If you want the highest index where the letter 'N' is present in your string, str.rfind() and str.rindex() are built exactly for this. The only difference between the two: rfind will return -1 in case of failure, rindex will raise ValueError instead. Or, if you want to loop backwards and append letters to a list starting from the end of the string:

a_list = []
a_string = 'this is a string'

for i in range(len(a_string)-1, -1, -1) :
    a_list.append(a_string[i])

print(a_list)
['g', 'n', 'i', 'r', 't', 's', ' ', 'a', ' ', 's', 'i', ' ', 's', 'i', 'h', 't']

Upvotes: 1

toshiro92
toshiro92

Reputation: 1344

You can access to the "N" variable, or 3 characters before i by doing :

for i,str in enumerate(myString):
    if str == "7":
       myList.append(myString[i-3])

Enumerate will begin with i=0 and will add 1 to i each time the loop will continue, but I will advise you to add a condition to avoid a negative number, and an error to myString[i-3], for instance:

for i,str in enumerate(myString):
    if (i > 2 and str == "7"):
       myList.append(myString[i-3])

Upvotes: 1

Syed Mehtab Hassan
Syed Mehtab Hassan

Reputation: 1337

Just loop on the string from last index to first and get that required element.

myString = "this is my striNg 7";
for (i = myString.length - 1; i > 0; i--) {
  if(myString[i]=='N'){
  console.log('index of N is ' +i);
  }
}

Upvotes: 0

Related Questions