Reputation: 3
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!
Upvotes: 0
Views: 1131
Reputation: 13
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.
Upvotes: 0
Reputation: 11
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)```
Upvotes: 0
Reputation: 1
Use the enumerate() method.
string = "AT ST!"
for i, s in enumerate(string[1:]:
quote = string[i] + s
print(quote)
Upvotes: 0
Reputation: 73470
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])
Upvotes: 2