这篇文章写的思路是这样的:
源码:
python3.6中的源码
运行代码:
我自己写的用例
很奇怪,运行代码首行都会添加一行 <span style="font-size:16px;">
这不是我写的啊,目前我也不会去掉。
运行结果:
...
结果说明:
对本方法使用的解释然后引出下一个方法
这样我就做到了阅读源码、积累单词、掌握用法,一箭双加一雕、一石二加一鸟、一举两加一得,哈哈O(∩_∩)O哈哈~。
说明一下,一切运行代码基于版本:python3.6
字符串方法的分类:
一、 大小写之类的
源码1:
| capitalize(...)
| S.capitalize() -> str
|
| Return a capitalized version of S, i.e. make the first character
| have upper case and the rest lower case.
运行代码:
strA = "my name is littlecurl"
v1 = strA.capitalize()
print('v1:',v1)
运行结果:
v1: My name is littlecurl
结果说明:
因为我写的 testa = "my name is littlecurl" 是一整个字符串,capitatlize() 不会把每个单词首字母大写,而只是把整个字符串的首字母变成大写。
如果要想把一整个字符串中的每个单词的首字母变成大写,其他变成小写,那么就需要下面这个方法title()
源码2:
| title(...)
| S.title() -> str
|
| Return a titlecased version of S, i.e. words start with title case
| characters, all remaining cased characters have lower case.
运行代码:
strB = "gone with the wind"
v2 = strB.title()
print('v2:',v2)
运行结果:
v2: Gone With The Wind
结果说明:
我写的这一整个字符串 strC = "gone with the wind" 中的每一个单词的首字母都变成了大写。
我又有一个全部大写的字符串 strD = "GONE WITH THE WIND",我想变成只把首字母小写,也就是
这样 "gONE wITH tHE wIND",虽然这里看的有点别扭,我想表达的意思就是,只把每个单词的首字母变小写,其他字母不变。经过我的思考,这样做,虽然可以用程序写出来,但是没有多大实际意义,我暂且不写这个程序了。但是,如果不是把首字母变成小写,而是把所有字母变成小写,那么就需要下面这个方法lower()
源码3:
| lower(...)
| S.lower() -> str
|
| Return a copy of the string S converted to lowercase.
运行代码:
strC = "GONE WITH THE WIND"
v3 = strC.lower()
print('v3:',v3)
运行结果:
v3: gone with the wind
结果说明:
这里的lower()对ASCII码中的字母都起作用,可以世界之大,不光有英语国家,比如说还有德语国家,德语中有一个大写的字母 ß 它对应的小写字母是 ss 用lower()就无法转换 ß 这个时候就需要用到下面这个方法 casefold()
源码4:
| casefold(...)
| S.casefold() -> str|
| Return a version of S suitable for caseless comparisons.
运行代码:
strD = "ß"
v4 = strD.casefold()
print('v4:',v4)
运行结果:
v4: ss
结果说明:
这里就不做过多解释了,就一句话,casefold() 虽然比 lower() 牛*,但是人们习惯用lower(),因为它比较容易记忆。当然了,既然有lower(), 如果没有 upper() 岂不是很尴尬?那就是下面这个方法upper()源码5:
| upper(...)
| S.upper() -> str
|
| Return a copy of S converted to uppercase.
运行代码:
strE = "gone with the wind"
v5 = strE.upper()
print('v5:',v5)
运行结果:
v5: GONE WITH THE WIND
结果说明:
现在已经能把字符串的整体在大小写之间切换了。但是,如果在整体之内,想把一个字符串中的大写变小写,小写变大写,那么就需要下面这个方法swapcase()源码6:
| swapcase(...)
| S.swapcase() -> str
|
| Return a copy of S with uppercase characters converted to lowercase
| and vice versa.
运行代码:
strF = "gONE wITH tHE wIND"
v6 = strF.swapcase()
print('v6:',v6)
运行结果:
v6: Gone With The Wind结果说明:
这里实现了字符串整体内的大写与小写的变换,大写变小写,小写变大写。
------------------------------------------分页了------------------------------------------
二、 查找、匹配、替换类的
源码7:
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
运行代码:
strG = "Gone With The Wind"
v7 = strG.index('The')
v7_1 = strG.index('The',0,13)
print('v7:',v7,'\nv7_1:',v7_1,'\nstrG[10]:',strG[10],'\nstrG[12]:',strG[12])
运行结果:
v7: 10v7_1: 10
strG[10]: T
strG[12]: e
结果说明:
从 v7 代码可以看到,index() 返回的是所匹配的子串的起始索引值
从v7_1代码可以看到,index() 可以指定匹配的范围
从我给出的两个索引,strG[10]: T strG[12]: e 结合 v7_1 中 strG.index('The',10,13) 可以看出,这里指定的匹配范围是一个左闭右开 [ ) 的区间,也就是说, The 这个词本来是从索引下表 10到12 但是用index()指定范围的时候,需要指定到右区间为13才能匹配到
index() 还有一个特性:如果,未匹配到,那么程序无法运行,会报错。当然,为了解决这个问题,就需要下面这个方法 find()
源码8:
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
运行代码:
strH = "Gone With The Wind"
v8 = strH.find('The')
v8_1 = strH.find('The',0,12)
print('v8:',v8,'\nv7_1:',v8_1,'\nstrH[10]:',strH[10],'\nstrH[12]:',strH[12])
运行结果:
v8: 10v7_1: -1
strH[10]: T
strH[12]: e
结果说明:
这里我把指定的范围给修改为 0 ,12 了,运行结果为 -1 ,这就保证了虽然为匹配到,但程序能正常运行。
总结一下,python中很多的区间范围都是左闭右开的 [ )
源码9:
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
| endswith(...)| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
运行代码:
strI = "Gone WitI TIe Wind"
v9 = strI.startswith('G')
v9_1 = strI.endswith('d')
print('v9:',v9,'\nv9_1:',v9_1)
运行结果:
v9: Truev9_1: True
结果说明:
这里注意到 startswith() 中间有个 s ,endswith() 中间也有个 s ,两个返回的都是布尔值
源码10:
| count(...)| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
运行代码:
strJ = "AAA3456AAA"
v10 = strJ.count('A')
v10_1 = strJ.count('A',0,3)
print('v10:',v10,'\nv10_1:',v10_1)
运行结果:
v10: 6v10_1: 3
结果说明:
这里的 count()就是对想要的字符串的计数、统计,也可以指定匹配范围,当然,也是左闭右开区间
源码11:
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}')
运行代码:
strK = "MY NAME IS {0}, AGE IS {1}"
strK_1 = "my name is {name}, age is {age}"
v11 = strK.format('LBJ',36)
v11_1 = strK_1.format(name='Scott',age=19)
v11_2 = strK_1.format_map({"name":"LBJ","age":36})
print(v11,'\n',v11_1,'\n',v11_2)
运行结果:
MY NAME IS LBJ , AGE IS 36my name is Scott, age is 19
my name is LBJ, age is 36
结果说明:
这里给出了三种格式化占位的方法,第一种是用索引占位,第二种是用变量占位,第一种索引占位赋值的方式比较纯粹简单,第二种变量占位赋值方式有两种,一是使用.format() 二是使用.format_map()
源码12:
| maketrans(x, y=None, z=None, /)
| Return a translation table usable for str.translate().|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
| translate(...)
| S.translate(table) -> str
|
| Return a copy of the string S in which each character has been mapped
| through the given translation table. The table must implement
| lookup/indexing via __getitem__, for instance a dictionary or list,
| mapping Unicode ordinals to Unicode ordinals, strings, or None. If
| this operation raises LookupError, the character is left untouched.
| Characters mapped to None are deleted.
运行代码:
strL = "I am a aaaeeeiiiooouuu"
v12= str.maketrans("aeiou","12345")
print(strL.translate(v12))
运行结果:
I 1m 1 111222333444555
结果说明:
maketrans() 和 translate() 搭配使用,先用 maketrans() 制作一个变量对应表,再用 translate() 对字符串进行遍历替换
如果不想这样一个一个字母对应着替换,而是替换掉一整块,那么需要下面这个方法 replace()
源码13:
| replace(...)
| S.replace(old, new[, count]) -> str
|
| Return a copy of S with all occurrences of substring
| old replaced by new. If the optional argument count is
| given, only the first count occurrences are replaced.
运行代码:
strM = "I am a aaaeeeiiiooouuu"
v13= strM.replace("aaaeeeiiiooouuu","student")
print(v13)
运行结果:
I am a student结果说明:
这里实现了整块的替换------------------------------------------分页了------------------------------------------
三、 自定义类的
复习的时候,如果上面的一个一个都看了下来,那么下面我就不在费事费力的按照格式写了,直接列出来方法。
源码14:
| S.expandtabs(tabsize=8) -> str
|
| Return a copy of S where all tab characters are expanded using spaces.
| If tabsize is not given, a tab size of 8 characters is assumed.
运行代码:
strN = "username\temail\tpassword\nlittlecurl\[email protected]\tqwe\nlittlecurl\[email protected]\tqwe\nlittlecurl\[email protected]\tqwe"
v14 = strN.expandtabs(20)
print(v14)
运行结果:
username email passwordlittlecurl [email protected] qwe
littlecurl [email protected] qwe
littlecurl [email protected] qwe
结果说明:
自定义制表符占位,运行代码中给出了 strN.expandtabs(20) 就是说,字符串strN中用 '\t' 分隔的每块都占20个位置,这样 '\t' '\n' 结合使用,就能造出一个表格样式的输出了。
#15.center() 自定义居中并填充
#16.ljust() rjust() 自定义左填充 右填充
#17.zfill() 自定义zero填充
#18.join() 自定义字符串连接
#19.zfill() 自定义zero填充
#20.strip() 默认去除两边的空格、换行、制表符等 lstrip() rstrip()默认去除左边、右边的空格、换行、制表符等
#可以自定义指定去除内容
#21.partition() rpartation() split() rsplit() 自定义保留分割、去除分割
#22.splitlines() 根据换行进行去除分割
四、判断数字、字母、标识符之类的
#不能有 空格、下划线等之类的
#24.isalpha() 字符串中是否仅包含字母
#不能有 数字、空格、下划线等之类的
#25.isdecimal() 判断字符串中是否是纯粹的十进制数字
#26.isdigit() 判断字符串中是否是数字,包含特殊形式的数字
#27.isnumeric() 判断是否是数字 包括中文,特殊符号的数字
#28.isidentifier() 判断是否是标识符 下划线、字母、数字
#29.isprintable() 是否全部是ASCII码中可打印的
#30.isspace() 是否全部是空格
---------------------------------------------------分页了----------------------------------------------------------
五、结束语
字符串里面大概就这三十个方法了,这些完全都不用刻意记忆、不用刻意记忆、不用刻意记忆
因为就是一个使用熟练程度的问题,熟能生巧的问题,你如果不是经常使用,记住也会忘掉的。忘掉也不用惊慌失措,想要用哪个,查一下手册就行了,当然查手册的前提是你像我这样一个一个过了一遍,有印象。
这里分享一个在线API文档链接: 在线API http://tool.oschina.net/apidocs