欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python 可爱的大小写

时间:2021-02-22 18:01:56|栏目:Python代码|点击:
函数较简单,看下面的例子:
复制代码 代码如下:

s = 'hEllo pYthon'
print s.upper()
print s.lower()
print s.capitalize()
print s.title()

输出结果:
HELLO PYTHON
hello python
Hello python
Hello Python


判断大小写
Python提供了isupper(),islower(),istitle()方法用来判断字符串的大小写。注意的是:
1. 没有提供 iscapitalize()方法,下面我们会自己实现,至于为什么Python没有为我们实现,就不得而知了。
2. 如果对空字符串使用isupper(),islower(),istitle(),返回的结果都为False。
复制代码 代码如下:

print 'A'.isupper() #True
print 'A'.islower() #False
print 'Python Is So Good'.istitle() #True
#print 'Dont do that!'.iscapitalize() #错误,不存在iscapitalize()方法


实现iscapitalize
1. 如果我们只是简单比较原字符串与进行了capitallize()转换的字符串的话,如果我们传入的原字符串为空字符串的话,返回结果会为True,这不符合我们上面提到的第2点。
def iscapitalized(s):
return s == s.capitalize( )有人想到返回时加入条件,判断len(s)>0,其实这样是有问题的,因为当我们调用iscapitalize('123')时,返回的是True,不是我们预期的结果。
2. 因此,我们回忆起了之前的translate方法,去判断字符串是否包含任何英文字母。实现如下:
复制代码 代码如下:

import string
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('123')
print iscapitalized('')
print iscapitalized('Evergreen is zcr1985')

输出结果:
False
False
True

上一篇:解析pip安装第三方库但PyCharm中却无法识别的问题及PyCharm安装第三方库的方法教程

栏    目:Python代码

下一篇:django中使用POST方法获取POST数据

本文标题:Python 可爱的大小写

本文地址:http://www.codeinn.net/misctech/67866.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有