Problem with for and if

29 views
Skip to first unread message

Dariusz Mysior

unread,
Jan 5, 2015, 9:32:06 AM1/5/15
to django...@googlegroups.com
I want search count of szukana in zmienna but code below counting all 12 letters from "traktorzysta" word

szukana="t"
zmienna
="traktorzysta"
 
 
def gen():
    count
=int(0)
   
for a in zmienna:
       
if szukana in zmienna:
            count
+=1
       
else:
           
continue
   
return count
 
 
print("Literka '",szukana,"' w słowie ",zmienna,
     
"wystąpiła ",gen()," razy")

Zoltán Bege

unread,
Jan 5, 2015, 10:45:19 AM1/5/15
to django...@googlegroups.com
You should use the string's count method: zmienna.count(szukana)

See help("string.count")
Message has been deleted

Erik Cederstrand

unread,
Jan 6, 2015, 8:39:50 AM1/6/15
to Django Users

> Den 05/01/2015 kl. 22.45 skrev Dariusz Mysior <mysior...@gmail.com>:
>
> I try develop this code to get a number of position this letter in word, and I have it but for example if i search letter "t" I get "1, 5, b", why I get b instead of 11???
>
> def gen2():
> count=0
> count2=0
> for a in zmienna:
> count2+=1
> if a==szukana:
> count+=1
> pozycja.append(count2)
>
> return pozycja
> print("3. Literka '",szukana,"' w słowie ",zmienna,
> "wystąpiła " ,gen(),"razy w kolejności")
> #print(gen2())
>
> print(", ".join(["%x" % a for a in gen2()]))

Whoa, that code is really convoluted. It won't even compile, as far as I can see. Try this instead:

import re
def indices(needle, haystack):
return [match.start() for match in re.finditer(re.escape(needle), haystack)]


If your search strings can be overlapping, you'll need another solution.

Erik
Reply all
Reply to author
Forward
0 new messages