Python天天美味(11) - 可爱的大小写

简介:

转换大小写

和其他语言一样,Python为string对象提供了转换大小写的方法:upper() 和 lower()。还不止这些,Python还为我们提供了首字母大写,其余小写的capitalize()方法,以及所有单词首字母大写,其余小写的title()方法。函数较简单,看下面的例子:
=   ' 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

Python 天天美味系列(总)

Python 天天美味(9) - translator  

Python 天天美味(10) - 除法小技巧  

Python 天天美味(11) - 可爱的大小写 
Python 天天美味(12) - 条件判断的缩写 

Python 天天美味(13) - struct.unpack   

...



本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/04/1181340.html,如需转载请自行联系原作者

目录
相关文章
|
11月前
|
存储 Python
[oeasy]python038_ range函数_大小写字母的起止范围_start_stop
本文介绍了Python中`range`函数的使用方法及其在生成大小写字母序号范围时的应用。通过示例展示了如何利用`range`和`for`循环输出指定范围内的数字,重点讲解了小写和大写字母对应的ASCII码值范围,并解释了`range`函数的参数(start, stop)以及为何不包括stop值的原因。最后,文章留下了关于为何`range`不包含stop值的问题,留待下一次讨论。
179 3
【Python 基础】如何将一个字符串转化为全大写和全小写?
【5月更文挑战第8天】【Python 基础】如何将一个字符串转化为全大写和全小写?
|
Python
python解决不区分大小写统计问题
python解决不区分大小写统计问题
107 0
|
存储 Unix Linux
Python将多个文件的名称或后缀名由大写字母修改为小写的方法
Python将多个文件的名称或后缀名由大写字母修改为小写的方法
146 1
python-capitalize() 方法:将字符串的第一个字符转换为大写,其余字符转换为小写
python-capitalize() 方法:将字符串的第一个字符转换为大写,其余字符转换为小写
75 0
python-lower() 方法:将字符串转换为小写
python-lower() 方法:将字符串转换为小写
71 0
python-返回字符串的小写和大写
python-返回字符串的小写和大写
78 0
|
Python
python取出字符串中的数字、字母、大小写字母
python取出字符串中的数字、字母、大小写字母
906 0
|
Python
Python 任意长度的人民币小写金额转大写的简短代码
Python 任意长度的人民币小写金额转大写的简短代码
476 0
[oeasy]python0018_ ASCII_字符分布_数字_大小写字母_符号_黑暗森林
[oeasy]python0018_ ASCII_字符分布_数字_大小写字母_符号_黑暗森林
173 0
[oeasy]python0018_ ASCII_字符分布_数字_大小写字母_符号_黑暗森林

热门文章

最新文章

推荐镜像

更多