python之转换大小写
和其他语言一样,Python为string对象提供了转换大小写的方法:upper()和lower()。还不止这些,Python还为我们提供了首字母大写,其余小写的capitalize()方法,以及所有单词首字母大写,其余小写的title()方法。函数较简单,看下面的例子:
s='hEllopYthon'
prints.upper()
prints.lower()
prints.capitalize()
prints.title()
输出结果:
HELLOPYTHON
hellopython
Hellopython
HelloPython
判断大小写
Python提供了isupper(),islower(),istitle()方法用来判断字符串的大小写。注意的是:
1.没有提供iscapitalize()方法,下面我们会自己实现,至于为什么Python没有为我们实现,就不得而知了。
2.如果对空字符串使用isupper(),islower(),istitle(),返回的结果都为False
print'A'.isupper()#True
print'A'.islower()#False
print'PythonIsSoGood'.istitle()#True
#print'Dontdothat!'.iscapitalize()#错误,不存在iscapitalize()方法
实现iscapitalize
1.如果我们只是简单比较原字符串与进行了capitallize()转换的字符串的话,如果我们传入的原字符串为空字符串的话,返回结果会为True,这不符合我们上面提到的第2点。
defiscapitalized(s):
returns==s.capitalize()
有人想到返回时加入条件,判断len(s)>0,其实这样是有问题的,因为当我们调用iscapitalize('123')时,返回的是True,不是我们预期的结果。
2.因此,我们回忆起了之前的translate方法,去判断字符串是否包含任何英文字母。实现如下:
importstring
notrans=string.maketrans('','')
defcontainsAny(str,strset):
returnlen(strset)!=len(strset.translate(notrans,str))
defiscapitalized(s):
returns==s.capitalize()andcontainsAny(s,string.letters)
#returns==s.capitalize()andlen(s)>0#如果s为数字组成的字符串,这个方法将行不通
调用一下试试:
printiscapitalized('123')
printiscapitalized('')
printiscapitalized('Evergreeniszcr1985')
输出结果:
False
False
True
以上内容为大家介绍了python之转换大小写,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:开发教育。http://www.baikegou.com/
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!