Python入门练习 - 字符串

Problem 1. Counting Vowels


Assume s is a string of lower case characters.

Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print:

Number of vowels: 5

For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined.

Answer


number = 0
n = 0
while n < len(s):
    if s[n] == 'a' or s[n] == 'e' or s[n] == 'i' 
or s[n] == 'o' or s[n] == 'u' :
        number = number +1
    n = n + 1
print ('Number of vowels: ' + str(number))

Problem 2. Counting Bobs


Assume s is a string of lower case characters.

Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print:

Number of times bob occurs is: 2

For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined.

Answer


number = 0
n = 0
while n < len(s)-2:
    if (s[n]+s[n+1]+s[n+2]) == 'bob':
        number = number +1
    n = n + 1
print ('Number of times bob occurs is: ' + str(number))

tag(s): none
show comments · back · home
Edit with markdown