Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
Python 字符串操作(string替换、删除、截取、复制、连接、比
较、查找、包含、大小写转换、分割等)
Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写
转换、分割等)
1. Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写
转换、分割等)
2.
3.
4. 去空格及特殊符号
5. s.strip() .lstrip() .rstrip(',') 6.
7. 复制字符串
8. #strcpy(sStr1,sStr)
9. sStr= 'strcpy'
10. sStr = sStr
11. sStr= 'strcpy'
12. print sStr
13.
14. 连接字符串
15. #strcat(sStr1,sStr) 16. sStr= 'strcat'
17. sStr = 'append' 18. sStr+= sStr
19. print sStr
20.
21. 查找字符
22. #strchr(sStr1,sStr) 23. sStr= 'strchr'
24. sStr = 's'
25. nPos = sStr1.index(sStr) 26. print nPos
27.
28. 比较字符串
29. #strcmp(sStr1,sStr) 30. sStr= 'strchr'
31. sStr = 'strch'
32. print cmp(sStr1,sStr) 33.
34. 扫描字符串是否包含指定的字符
35. #strspn(sStr1,sStr) 36. sStr= '1345678' 37. sStr = '456'
38. #sStrand chars both in sStrand sStr
39. print len(sStrand sStr) 40.
41. 字符串长度
42. #strlen(sStr1) 43. sStr= 'strlen' 44. print len(sStr1) 45.
46. 将字符串中的大小写转换 47. #strlwr(sStr1) 48. sStr= 'JCstrlwr' 49. sStr= sStr1.upper() 50. #sStr= sStr1.lower() 51. print sStr
52.
53. 追加指定长度的字符串 54. #strncat(sStr1,sStr,n) 55. sStr= '1345'
56. sStr = 'abcdef' 57. n = 3
58. sStr+= sStr[0:n] 59. print sStr
60.
61. 字符串指定长度比较 62. #strncmp(sStr1,sStr,n) 63. sStr= '1345'
64. sStr = '13bc' 65. n = 3
66. print cmp(sStr1[0:n],sStr[0:n])
67.
68. 复制指定长度的字符 69. #strncpy(sStr1,sStr,n) 70. sStr= ''
71. sStr = '1345' 72. n = 3
73. sStr= sStr[0:n] 74. print sStr
75.
76. 将字符串前n个字符替换为指定的字符
77. #strnset(sStr1,ch,n) 78. sStr= '1345'
79. ch = 'r'
80. n = 3
81. sStr= n * ch + sStr1[3:] 82. print sStr
83.
84. 扫描字符串
85. #strpbrk(sStr1,sStr) 86. sStr= 'cekjgdklab' 87. sStr = 'gka'
88. nPos = -1
89. for c in sStr1: 90. if c in sStr: 91. nPos = sStr1.index(c)
92. break
93. print nPos
94.
95. 翻转字符串
96. #strrev(sStr1)
97. sStr= 'abcdefg' 98. sStr= sStr1[::-1] 99. print sStr
100.
101. 查找字符串
102. #strstr(sStr1,sStr) 103. sStr= 'abcdefg' 104. sStr = 'cde'
105. print sStr1.find(sStr) 106.
107. 分割字符串
108. #strtok(sStr1,sStr) 109. sStr= 'ab,cde,fgh,ijk' 110. sStr = ','
111. sStr= sStr1[sStr1.find(sStr) + 1:]
112. print sStr
113. 或者
114. s = 'ab,cde,fgh,ijk' 115. print(s.split(',')) 116.
117. 连接字符串
118. delimiter = ',' 119. mylist = ['Brazil', 'Russia', 'India', 'China']
120. print delimiter.join(mylist) 121. PHP 中 addslashes 的实现 122. def addslashes(s):
123. d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"} 124. return ''.join(d.get(c, c) for c in s) 125. s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0" 126. print s
127. print addslashes(s)
128.
129. 只显示字母与数字
130. def OnlyCharNum(s,oth=''):
131. s = s.lower();
132. fomart = 'abcdefghijklmnopqrstuvwxyz013456789' 133. for c in s:
134. if not c in fomart:
135. s = s.replace(c,'');
136. return s;
137. print(OnlyStr("a000 aa-b"))