1 #coding:utf-8
2 #兩個小函數
3 #一、尋找字元在字串中第一次出現的位置.
4 def find(string, char):
5 index = 0
6 while index < len(string):
7 if (string[index] == char):
8 return index
9 index += 1
10 return -1
11
12 #二、尋找字元在字串中的總數
13 def findSum(string, char):
14 index = 0
15 count = 0
16 while index < len(string):
17 if (string[index] == char):
18 count += 1
19 index += 1
20 return count
21
22 #使用以上兩個函數
23 print "字元1在字串1211211234中第一次出現的位置: ", find("1211211234", "1")
24 print "字元1在字串1211211234中出現的次數:", findSum("1211211234", "1")
25
26 import string #引入string庫
27 print string.find('www.cctv.com', 'com') #result=9
28 print string.find('Good','d') #result = 3
29 print string.find('canada', 'a',2,9) #result =3,用法如下:
30 #string.find(s, sub[, start[, end]])函數說明
31 #Return the lowest index in s where the substring sub is found such that sub is
32 #wholly contained in s[start:end]. Return -1 on failure. Defaults for start and
33 #end and interpretation of negative values is the same as for slices.
34 print string.lowercase #常量,abcdefghijklmnopqrstuvwxyz
35 print string.uppercase #常量,ABCDEFGHIJKLMNOPQRSTUVWXYZ
36 print string.digits #常量,0123456789
37
38 def isLower(char): #判斷一個字元是否為小寫
39 if (string.find(string.lowercase, char) > -1):
40 return 'Good'
41 return 'bad'
42 print isLower('S')
43
44 def isLowertest(char): #另外一種判斷字元是否為小寫方法
45 return char in string.lowercase
46 print isLowertest('a')
47