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.mobiletrain.org/

相关推荐HOT
更多>>
python中的变量怎么设置
python中变量设置方法:变量存储在内存中的值。这就意味着在创建变量时会在内存中开辟一个空间。基于变量的数据类型,解释器会分配指定内存,并...详情>>
2023-11-09 23:53:16
python中t是什么意思?
python中t指的是“\r”:回车符,返回到这一行的开头,return的意思。其他相关:>>\n:换行符,到下一行的同一位置,纵坐标相同,newline的意思...详情>>
2023-11-09 18:48:52
python 学习十阶段
第一阶段:Python基础知识—核心Python开发环境布置程序的构成变量、标识符、布尔运算、字符串机制、分支语句、逻辑表达式;局部变量和全局变量...详情>>
2023-11-09 15:36:18
python 的内置字典
python内置了字典:dict(key-value存储方式)的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速...详情>>
2023-11-09 15:16:10