I recently got a project in which I need to find all of the indices where a specific character appeared in a string inputted by the user. For example the user inputs the string "This is a test" and I wanted to find the indices of all the t's in the string I would get 0, 11, 14 I looked through the built in commands and couldn't find anything so it would be a real help to know a method to find this.
            Asked
            
        
        
            Active
            
        
            Viewed 64 times
        
    2 Answers
2
            
            
        Use enumerate and a list comprehension:
st="This is a test"
print([i for i, c in enumerate(st) if c.lower()=='t'])
Or:
print([i for i, c in enumerate(st) if c in 'tT'])
In either case, prints:
[0, 10, 13]
Explanation
First thing that 'makes this work' is that strings are iterable in Python:
>>> st="This is a test"
>>> for c in st:
...    print c
... 
T
h
i
s
i
s
a
t
e
s
t
Second thing that makes this work is enumerate which adds a count of all the characters in the string as a tuple:
>>> for tup in enumerate(st):
...    print tup
... 
(0, 'T')
(1, 'h')
(2, 'i')
(3, 's')
(4, ' ')
(5, 'i')
(6, 's')
(7, ' ')
(8, 'a')
(9, ' ')
(10, 't')
(11, 'e')
(12, 's')
(13, 't')
Pulling those two concepts together into a list comprehension produces the result:
[i for i, c in enumerate(st) if c.lower()=='t']
                 ^^^                               Produces the tuple of index and character
       ^  ^                                        Index, Character
                                  ^^^^^^^^^^^      test the character if it is 't'
 ^                                                 What is wanted - list of indices
 
    
    
        dawg
        
- 98,345
- 23
- 131
- 206
- 
                    Thank you this works, can you just explain why it works, I would like to understand the workings behind the code – user3277658 Feb 08 '14 at 17:59
0
            
            
        Just a straightforward approach as an alternative to a (better) enumerate option:
[range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']
 
    
    
        sashkello
        
- 17,306
- 24
- 81
- 109
 
    