Reputation: 47
import re
palabra="hola mundo"
caracter="o"
buscacaracter=(re.search(caracter,palabra))
print(buscacaracter)
So in this code it search until the first "o" is found but it doesn't count the last "o".
Is there a way to find every "o"?
This happens with these methods as well:
print(buscacaracter.start())
print(buscacaracter.end())
print(buscacaracter.span())
And when I use this method:
(re.findall(caracter,palabra))
it doesn't return the positions of the "o", just the number of them.
Upvotes: 1
Views: 74
Reputation: 103714
If you just want the index of each caracter
it is faster, easier to use enumerate:
palabra="hola mundo"
caracter="o"
>>> [i for i,c in enumerate(palabra) if c==caracter]
[1, 9]
If you want a regex, use finditer which return a match object which contains the index:
>>> [m.span()[0] for m in re.finditer(rf'{caracter}', palabra)]
[1, 9]
Upvotes: 1