Python Cookbook学习记录 ch1_12_2013/10/24
ch1_11 PASS
1.12 控制大小写
首先是大家都很熟悉的upper()和lower()
文中还介绍了capitalize()和title(),capitalize()的作用是将第一个字符改成大写,第二个字符是将每个单词的第一个字符转成大写
>>> print 'hello world!'.capitalize() Hello world! >>> print 'hello world!'.title() Hello World!
讨论:
写一个iscapitalized(s)函数,来判断字符串是不是首字符大写
>>> def iscapitalized(s): return s == s.capitalize() >>> iscapitalized('Hello World!') False >>> iscapitalized('hello world') False >>> iscapitalized('Hello world!') #只有首字符大写,PASS True
但是这种方法对于空字符和不含字母的字符串也会返回True
>>> iscapitalized(' ') True
更严格的代码:使用了前几节介绍的maketrans和translate方法,只有存在字符的情况下才返回True
书中有一个错误,就是在iscapitalized函数中调用containAny时将参数顺序弄反了。
>>> import string >>> notrans = string.maketrans('','') >>> def containAny(strs,strset): return len(strset) != len(strset.translate(notrans,strs)) >>> def iscapitalized(s): return s == s.capitalize() and containAny(string.letters,s) >>> iscapitalized('Hello world!') True >>> iscapitalized(' ') False