How to find the number value set to a specific character within a string (without counting) in python -
this question has answer here:
- how find occurrences of element in list? 8 answers
- how find occurrences of element in list? 2 answers
i got project in need find of indices specific character appeared in string inputted user. example user inputs string "this test" , wanted find indices of t's in string 0, 11, 14 looked through built in commands , couldn't find real know method find this.
use enumerate , list comprehension:
st="this test" print([i i, c in enumerate(st) if c.lower()=='t'])
or:
print([i i, c in enumerate(st) if c in 'tt'])
in either case, prints:
[0, 10, 13]
explanation
first thing 'makes work' strings iterable in python:
>>> st="this test" >>> c in st: ... print c ... t h s s t e s t
second thing makes work enumerate adds count of characters in string tuple:
>>> 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 2 concepts list comprehension produces result:
[i i, c in enumerate(st) if c.lower()=='t'] ^^^ produces tuple of index , character ^ ^ index, character ^^^^^^^^^^^ test character if 't' ^ wanted - list of indices
Comments
Post a Comment