平时写程序,没怎么看Python源码,不看不知道,一看吓一跳,原来Python大神实现的源码中,
已经包含了很多平时我们用到的功能,这样就不用再造轮子了。
对于str这个类,发现几个有用的方法:
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> str Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return ""
这个函数是返回以当前字符串为中间的一个串,填充值为fillchar,如果长度小于原字符串,则返回原串。
这个就非常有用,比如,想要输出一个文章标题,标题居中显示,可以这样使用,fillchar等于空格就可以了。
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ 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. """ return False
是否以指定串结束,与之对应的还有个startswith函数。其中,可以指定其开始和结束地址。
发现,很多的Python函数都提供了默认参数,只是平时用得不多,导致其很多的功能都不知道。
对于排版,则还有个函数不得不提:
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__ """ 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. """ return ""
这个函数是将\t(注意只能是它,不能是Python代码中的缩进空格)转换成空格,你可以指定转换的空格的数量。
比如str = "abc\tdefg\tfdad\t"
则可以将其排版成下面这样:
abc defg tfdad
这样在多行显示时,则看起来是非常好看的。
对于 字符串,判断其开头第一个字母是不是数字,字母等,这个在不自己实现的情况下,完全可以参考
Python的源码,其可能实现了,看源码,一方面可以提供代码水平,另外,使用系统自己的函数,也更加高效。
def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return Falseuttf
首字母是否大写,这个一定也有这样的方法,这里就不再列举了。
养成 一个好习惯,写程序,一定要先看源码。说不定会有惊喜出现。