2nd iteration of a character
Emile van Sebille
emile at fenx.com
Mon Sep 22 15:38:01 EDT 2003
> How do I find the second iteration of a character in a string using python
>
> this gives me the first one
> f1 = string.find(line,sub)
>
> this the last one
> f2 = string.rfind(line,sub)
>
> but for the nth one ?
>
You've already got some good answers, so how about (-:
>>> def nth(s,ss,n): return n<len(s.split(ss)) and
len(ss.join(s.split(ss)[:n]))
...
>>> s = 'this is a test this is a test'
>>> nth(s,'t',7)
False
>>> nth(s,'t',5)
25
>>> nth(s,'i',2)
5
>>> nth(s,'x',2)
False
>>>
Emile van Sebille
emile at fenx.com
More information about the Python-list
mailing list