[关闭]
@nalan90 2017-07-28T17:31:22.000000Z 字数 2165 阅读 609

专题四 string常用操作

Python高效编程技巧实战


常用函数
常用操作
  1. In [69]: name = 'zhangshuang'
  2. ## 字符串首字母大写
  3. In [70]: name.capitalize()
  4. Out[70]: 'Zhangshuang'
  5. In [86]: name = 'zhang shuang'
  6. In [87]: name.capitalize()
  7. Out[87]: 'Zhang shuang'
  8. ## 字符串中每个单词首字母大写
  9. In [85]: name.title()
  10. Out[85]: ' Zhangshuang '
  11. In [88]: name.title()
  12. Out[88]: 'Zhang Shuang'
  13. ## 字符串拆分
  14. In [89]: name.split()
  15. Out[89]: ['zhang', 'shuang']
  16. ## 将字符串转化为unicode编码格式
  17. In [71]: name.decode()
  18. Out[71]: u'zhangshuang'
  19. In [72]: name.isdigit()
  20. Out[72]: False
  21. ## 判断是否以指定字符串开头
  22. In [73]: name.endswith('shuang')
  23. Out[73]: True
  24. ## 判断是否以指定字符串结尾
  25. In [74]: name.startswith('zhangs')
  26. Out[74]: True
  27. In [75]: name = u'张爽'
  28. ## 将字符串从unicode处理成utf-8编码
  29. In [76]: name.encode('utf-8')
  30. Out[76]: '\xe5\xbc\xa0\xe7\x88\xbd'
  31. In [77]: l = ['this','is','a','test','string']
  32. ## 将列表处理成字符串,以指定字符分隔
  33. In [78]: ' '.join(l)
  34. Out[78]: 'this is a test string'
  35. In [79]: name = ' zhangshuang '
  36. ## 去掉首尾空格
  37. In [80]: name.strip()
  38. Out[80]: 'zhangshuang'
  39. In [81]: name.lstrip()
  40. Out[81]: 'zhangshuang '
  41. In [82]: name.rstrip()
  42. Out[82]: ' zhangshuang'
  43. ## 去掉最右边指定字符
  44. In [83]: sql = 'insert into table values(a,b,c),(d,e,f),'
  45. In [84]: sql.rstrip(',')
  46. Out[84]: 'insert into table values(a,b,c),(d,e,f)'
  47. ## 统计指定字符串出现的次数
  48. In [92]: name.count('a')
  49. Out[92]: 2
  50. ## 字符串大小写转化
  51. In [95]: name
  52. Out[95]: 'zhang shuang'
  53. In [94]: name.upper()
  54. Out[94]: 'ZHANG SHUANG'
  55. In [96]: name = 'Zhang Shuang'
  56. In [97]: name.lower()
  57. Out[97]: 'zhang shuang'
  58. ## 字符串查找
  59. In [100]: name = 'zhangshuang'
  60. In [123]: name.find('h')
  61. Out[123]: 1
  62. In [124]: name.find('S')
  63. Out[124]: -1
  64. ## 字符串格式化
  65. In [103]: 'My name is %s' % (name)
  66. Out[103]: 'My name is zhangshuang'
  67. In [104]: 'My name is {name}'.format(name=name)
  68. Out[104]: 'My name is zhangshuang'
  69. In [110]: 'My name is {name}, I am {age} years old'.format(name='zhangshuang',age=27)
  70. Out[110]: 'My name is zhangshuang, I am 27 years old'
  71. In [108]: 'My name is {0}, I am {1} years old'.format('zhangshuang',27)
  72. Out[108]: 'My name is zhangshuang, I am 27 years old'
  73. ## 替换指定字符串
  74. In [112]: name = 'zhang shuang'
  75. In [115]: name.replace('h','S')
  76. Out[115]: 'zSang sSuang'
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注