categories | date | title | url | |
---|---|---|---|---|
|
2008-05-04 |
Python天天美味(11) - 可爱的大小写 |
/2008/05/04/1181340/ |
和其他语言一样,Python为string对象提供了转换大小写的方法:upper() 和 lower()。还不止这些,Python还为我们提供了首字母大写,其余小写的capitalize()方法,以及所有单词首字母大写,其余小写的title()方法。函数较简单,看下面的例子:
print s.upper()
print s.lower()
print s.capitalize()
print s.title()
输出结果:
HELLO PYTHON
hello python
Hello python
Hello Python
Python提供了isupper(),islower(),istitle()方法用来判断字符串的大小写。注意的是:
-
没有提供 iscapitalize()方法,下面我们会自己实现,至于为什么Python没有为我们实现,就不得而知了。
-
如果对空字符串使用isupper(),islower(),istitle(),返回的结果都为False。
print 'A'.islower() #False
print 'Python Is So Good'.istitle() #True
#print 'Dont do that!'.iscapitalize() #错误,不存在iscapitalize()方法
- 如果我们只是简单比较原字符串与进行了capitallize()转换的字符串的话,如果我们传入的原字符串为空字符串的话,返回结果会为True,这不符合我们上面提到的第2点。
return s == s.capitalize( )
- 因此,我们回忆起了之前的translate方法,去判断字符串是否包含任何英文字母。实现如下:
notrans = string.maketrans('', '')
def containsAny(str, strset):
return len(strset) != len(strset.translate(notrans, str))
def iscapitalized(s):
return s == s.capitalize( ) and containsAny(s, string.letters)
#return s == s.capitalize( ) and len(s) > 0 #如果s为数字组成的字符串,这个方法将行不通
print iscapitalized('')
print iscapitalized('Evergreen is zcr1985')
输出结果:
False
False
True
Python 天天美味(13) - struct.unpack
[温馨提示]:该文章由原博客园导入而来,如排版效果不佳,请移步:http://www.cnblogs.com/coderzh/archive/2008/05/04/1181340.html