Python对字母字符(串)中大小写转换函数--upper() 和 lower()
来源:互联网 发布:zip解压软件下载mac 编辑:程序博客网 时间:2024/06/05 14:52
转换大小写
和其他语言一样,Python为string对象提供了转换大小写的方法:upper() 和 lower()。还不止这些,Python还为我们提供了首字母大写,其余小写的capitalize()方法,以及所有单词首字母大写,其余小写的title()方法。函数较简单,看下面的例子:s = 'hEllo pYthon'
print s.upper()
print s.lower()
print s.capitalize()
print s.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()方法用来判断字符串的大小写。注意的是: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()方法
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,不是我们预期的结果。return s == s.capitalize( )
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为数字组成的字符串,这个方法将行不通
调用一下试试: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')
print iscapitalized('')
print iscapitalized('Evergreen is zcr1985')
输出结果:
False
False
True
- Python对字母字符(串)中大小写转换函数--upper() 和 lower()
- Python对字母字符(串)中大小写转换函数--upper() 和 lower()
- python中改变字母大小写的函数upper()和lower()
- Python 中的lower()、upper()函数和str\chr
- SQL 标量函数----->字符串函数 之一 字符转换函数 ASCII() 、CHAR()、LOWER()、UPPER()、STR()
- oracle lower函数和upper函数
- Oracle lower(Upper)函数
- oracle-lower(),upper()函数
- mysql 并 concat 和 大小写转换 UPPER
- php中字母大小写转换函数
- php中字母大小写转换函数
- python upper(),lower(),title(),capitalize()
- python 列表生成式、lower()和upper()的使用
- 对于BST(二分搜索树)中lower 和upper的技巧
- lower-bound和upper-bound
- Python upper() 函数 转换为大写字母
- C++ 中字符大小写转换的函数
- SQL 字母大小写转换 函数
- execve函数簇
- autoit3——打开窗口
- 不要用retainCount来获得对象的引用次数
- 已知二叉树后序遍历序列是DBCEFGHA,中序遍历序列EDCBAHFG,它的前序遍历的序列是?
- Extjs-表格 Ext.grid.GridPanel
- Python对字母字符(串)中大小写转换函数--upper() 和 lower()
- Xcode快捷键
- linux内存管理之伙伴系统(内存分配)
- 金华邀请赛B题poj 4046(spfa求最短路)
- 数据区,代码区,堆栈区,操作系统堆栈
- 另类的旁注方式 seesion欺骗+dns欺骗 登陆 -> 注册 -> 搜索 分享
- <A HREF="" target="_BLANK">打开的新窗口大小的控制
- Apache多路处理模块(MPM)之prefork和worker的配置
- java(JDBC连接数据库)[完整版封装]