- counting vowels:
计算字符串中含有元音字母aeiou
的数量1 char = 'azcbobobegghakl' 2 num = 0 3 #利用in方法直接查找字符串char中含有的元音字母数量 4 for char in 'aeiou': 5 num += 1 6 print ("Number of vowels: " + str(num))
- counting bobs:
查找字符串中含有子串‘bob’的数量1 count = 0 2 s = 'azcbobobegghakl' 3 #range()方法:当i大于0小于字符串s的长度时 4 for i in range(0,len(s)): 5 #如果从s中截取3位长度的子串等于‘bob’时,将计数加一 6 if s[i:i+3] == 'bob': 7 count += 1 8 print(count)
- ALPHABETICAL SUBSTRINGS:
查找字符串中按字母顺序排列的最长子串,比如azcbobobegghakl
则输出beggh
1 s = "azcbobobegghakl" 2 start = 0 3 end = 0 4 temp_start = 0 5 6 for i in range(1, len(s)): 7 if s[i-1] > s[i]: 8 temp_start = i 9 10 if i - temp_start > end - start: 11 start = temp_start 12 end = i 13 14 print('Longest substring in alphabetical order is:', s[start:end+1])