Python字符串在实际中的操作手册


Python字符串在使用的时候是需要我们进行详细的学习。下面我们就看看在具体的操作中如何才能更好的进行这个字符串的使用方法。在之后的使用中还是需要我们继续学习。

  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 += 11  
  10. return -111   
  11. #二、查找字符在字符串中的总数  
  12. def findSum(string, char):  
  13. index = 0 
  14. count = 0 
  15. while index < len(string):  
  16. if (string[index] == char):  
  17. count += 1  
  18. index += 1  
  19. return count  
  20. #使用以上两个函数  
  21. print "字符1在字符串1211211234中第一次出现的位置: ", find("1211
    211234", "1")  
  22. print "字符1在字符串1211211234中出现的次数:", findSum("1211211
    234", "1")  
  23. import string #引入string库  
  24. print string.find('www.cctv.com', 'com') #result=9 
  25.  print string.find('Good','d') #result = 3 
  26. print string.find('canada', 'a',2,9) #result =3,用法如下:  
  27. #string.find(s, sub[, start[, end]])函数说明  
  28. #Return the lowest index in s where the substring sub is 
    found such that sub is  
  29. #wholly contained in s[start:end]. Return -1 on failure. 
    Defaults for start and  
  30. #end and interpretation of negative values is the same 
    as for slices.  
  31. print string.lowercase #常量,abcdefghijklmnopqrstuvwxyz  
  32. print string.uppercase #常量,ABCDEFGHIJKLMNOPQRSTUVWXYZ  
  33. print string.digits #常量,012345678937   
  34. def isLower(char): #判断一个字符是否为小写  
  35. if (string.find(string.lowercase, char) > -1):  
  36. return 'Good'  
  37. return 'bad'  
  38. print isLower('S')  
  39. def isLowertest(char): #另外一种判断字符是否为小写的方法  
  40. return char in string.lowercase46 print isLowertest('a')  

以上就是对Python字符串的相关介绍,希望大家有所收获。

评论关闭