0

Python novice. I'm looping through a string, and I need to be able to index the location of each character in the string. However, .index() just gives me the first time the character pops up, and I need the location of the exact character I'm looping through.

string = "AT ST!"
for i in string[1:]:
    ind = string.index(i)      #only finds first instance
    quote = string[ind-1] + i
    print(quote)

Let's say I want this to return

AT
T 
 S
ST   #what I want
T!

but instead it would return

AT
T 
 S
AT   #heck
T!

Any help would be appreciated!

4 Answers 4

2

You can use enumerate to iterate indeces and chars in parallel:

for ind, i in enumerate(string[1:], 1):
    quote = string[ind-1] + i
    print(quote)

Or even better, use slices:

for i in range(1, len(string)):
    print(string[i-1:i+1])
Sign up to request clarification or add additional context in comments.

Comments

0

Use the enumerate() method.

string = "AT ST!"
for i, s in enumerate(string[1:]:
    quote = string[i] + s
    print(quote)

Comments

0

In this kind of scenario its better not to use index as is suggested by schwobaseggl. But Just for the sake of using index in this example below is the way you can use it. index can take parameters of start and end index so it will only search between those indexes so you can pass the current index as starting index in this example.

list.index(element, start, end)

for ind,i in enumerate(string[1:],1):
    ind = string.index(i,ind)     
    quote = string[ind-1] + i
    print(quote)```

Comments

0

You could attain this by looping through the index position using the range and len functions in python like this:

string = "AT ST!"  
for i in range(len(string) - 1):  
    print(string[i]+string[i+1])

The .index() function is working as it is supposed to, it actually starts searching from the first index.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.