I am trying to count how many o's there are in the raw input 'phrase' and it counts the first o and says it's done however there are many o's after that. How do I get it to count all of the o's with no for loop.
while loop_count<len(phrase):
if "o" in phrase:
loop_count += 1
count2 += 1
if loop_count>len(phrase):
print loop_count
break
else:
continue
else:
print loop_count
continue
You can use sum with an iterator (in this case a generator expression ):
>>> sum(c=='o' for c in 'oompa loompa')
4
You can use a regex with len:
>>> re.findall('o', 'oompa loompa')
['o', 'o', 'o', 'o']
>>> len(re.findall('o', 'oompa loompa'))
4
You could use a Counter:
>>> from collections import Counter
>>> Counter('oompa loompa')['o']
4
Or just use the 'count' method of the string:
>>> 'oompa loompa'.count('o')
4
If you really want to use a while loop, use a list as a stack with the pop method:
s='oompa loompa'
tgt=list(s)
count=0
while tgt:
if tgt.pop()=='o':
count+=1
Or a 'for' loop -- more Pythonic:
count=0
for c in s:
if c=='o':
count+=1
you can use count
function :
phrase.count('o')
but if you want to send a message after one match of 'o' for skip loop over the all of string just use 'in' look like this:
if 'o' in phrase :
# show your message ex: print('this is false')
Lets try to dissect your code you understand what is going on. See my comments
while loop_count<len(phrase):
if "o" in phrase: # See comment 1
loop_count += 1 # Why are you incrementing both of these?
count2 += 1
if loop_count>len(phrase): # What is this statement for? It should never happen.
## A loop always exits once the condition at the while line is false
## It seems like you are manually trying to control your loop
## Which you dont need to do
print loop_count
break # What does this accomplish?
else:
continue
else:
print loop_count
continue # Pointless as we are already at end of loop. Consider removing
Comment 1: You are asking if an 'o' is anywhere in the phrase. You instead want to ask if the current letter is an o. Perhaps you ment to access a LETTER of the phrase with the index, such as if 'o' == phrase[loop_count]
. If you do this you want to increment loop_count every time, but the o count only when the letter is an o.
You could re-write it like this:
loop_count, o_count = 0, 0
while loop_count<len(phrase):
# loop_count represents how many times we have looped so far
if "o" == phrase[loop_count].lower(): # We ask if the current letter is 'o'
o_count += 1 # If it is an 'o', increment count
loop_count += 1 # Increment this every time, it tracks our loop count
print o_count
使用理解
len([i for i in phrase if i=="o"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.