Reputation: 13
I've been given this string and this index position and I'm trying to find the index position while skipping over the "D" characters.
s="MMMMMMMMDDDDDDDMMMMMMIIMMDDDDDDDDDDDMMMMMMM"
tr1 = 13
As of right now I have this code:
for x in range(tr1):
if s[x] == "D":
continue
else:
print (s[x], x+1)
I should be getting a position of 23
Upvotes: 1
Views: 182
Reputation: 451
Here's a one-liner that should do the trick:
[i for _,i in enumerate(s) if i!='D'][13
Upvotes: 0
Reputation: 1002
Is this what you are looking for ? I used reg ex to get rid of the uppercase Ds and then indexing ([13]) to retrieve 13th position starting from 0
import re
s="MMMMMMMMDDDDDDDMMMMMMIIMMDDDDDDDDDDDMMMMMMM"
print (re.findall("[^D]",s)[13])
> 'M'
If you want to see data for the original string (including D):
print (s[13])
>'D'
Upvotes: 0
Reputation: 367
I am not sure what exactly do you want but if i understand right, you want the char in 13th position and you dont want to count chars equal to 'D'. In your for loop, you are just checking the first 13th char because you put tr1 in range!
so the code you want should be something like this:
count=0
for x in range(len(s)):
if s[x] == "D":
continue
else:
count +=1
if (count == 13):
print (s[x], x+1)
break
and if you want to fine the position of char "I", the code should be:
count=0
for x in range(len(s)):
if s[x] == "D":
continue
else:
count +=1
if (count >= 13):
if (s[x] == "I"):
print (s[x], x+1)
In this way you can have index 23 that you mentioned before
Upvotes: 0
Reputation: 513
I don't understand why should you get 23? Is your code doing what you want? Since you are using range()
function your code stops after 13 iterations is that what you want? If you want to print all characters that are not 'D' along with their index+1 I would rather do the following:
for i, char in enumerate(s):
if char != 'D':
print(char, i+1)
If instead you want to stop the for loop at the first 'D' found just add a break statement like this:
for i, char in enumerate(s):
if char != 'D':
print(char, i+1)
elif char == 'D':
break #stop at first 'D' found
Where is your 23 should be coming from?
Upvotes: 1