0
点赞
收藏
分享

微信扫一扫

python字符串内建函数操作实例(cmp、str、enumerate、zip等)

#coding=utf8
'''
cmp(str1,str2):根据字符串的ASCII码值进比较,返回一个整数。
如果返回值大于零,str1大于str2;
如果返回值小于零,str1小于str2;
如果返回值等于零,str1等于str2;

len(object):返回序列的长度,取决于object对象类型。
如果是字符串,则返回字符串的字符数;
如果是列表、元组,则返回列表的元素个数;
如果是字典,则返回键值对个数

max(str):对于string类型,返回最大的字符(按照ASCII码值排序)
min(str):对于string类型,返回最小的字符(按照ASCII码值排序)

enumerate(string):返回string的索引和对应索引位的值。

zip():参数为两个,两个参数的长度要相同才能进行zip操作,返回一个元组list
以string类型为例,对两个同样长度的string,对应位置组合成一个元组,
把这些元组放入一个List中。

raw_input():是一个输入函数,输入什么就把输入的结果返回,不进行任何处理。

str(object):创建一个sting类的对象。
unicode(object):创建一个unicode类型的对象。
str和unicode可以像basestring一样作为参数传给isinstance()函数来判断一个对象的类型。

chr(intobject):intobject是一个(0-255)整数,返回一个对应的字符串。
unichr(intobject):返回的是Unicode 字符,
unichr(intobject)从Python2.0 才加入,intobject范围依赖于Python 是如何被编译的.
如果是配置为USC2 的Unicode,那么它的允许范围就是range(65536) 或者说0x0000-0xFFFF;
如果配置为UCS4 , 那么这个值应该是range(1114112)或者0x000000-0x110000.
如果提供的参数不在允许的范围内,则会报一个ValueError 的异常。

ord(char):char是长度为一的字符串,返回对应字符的ASCII数值或者Unicode数值。
如果所给的Unicode字符超过Python定义范围,会引发一个TypeError异常。
'''

def callBuildInFunc():
'''调用cmp函数'''
#如果hello大于Hello输出hello
if cmp("hello","Hello")>0:
print "hello"
#如果hello ewang和hello ewang相等输出hello ewang
if cmp("hello ewang","hello ewang")==0:
print "hello ewang"
#如果hello"小于"shutdown",输出shutdown
if cmp("hello","shutdown")<0:
print "shutdown"

'''调用len函数'''
#求打印一个字符串长度
print len("hello ewang")
#打印一个list的长度
print len([1,"love",3,"you",5,"me",6])
#打印在一个字典的键值对个数
print len({"a":ord("a"),"b":ord("b")})

'''调用max和min函数'''
#打印一个字符串最大字符
print max("abc")
#打印一个字符串最小字符
print min("hello")

'''调用enumerate()函数'''
#输出字符串的索引和对应索引的值
string="good idea"
for index,value in enumerate(string):
print index,"------>",value

#输出list的索引和对应索引的值
stringList=["good",1,123,12.36,"idea"]
for index,value in enumerate(stringList):
print index,"------>",value

'''调用zip函数'''
#把两个字符串进行zip
one="123456"
two="654321"
print zip(one,two)

#把字符串和其对应的ascii列表
stringD="ABCabcDhELO"
charassc=[]
for var in stringD:
#获取对应元素的ASCII值
ordin=ord(var)
#把ASCII值放入charassc列表
charassc.append(ordin)
#把列表和字符串进行zip操作
print zip(stringD,charassc)

'''调用str()、unicode()、isinstance()函数'''
#判断对象是否是str对象
if isinstance(u"you ara a beautiful",str):
print u"\0xAB"
#判断对象是否是unicode对象
if not isinstance('good food', unicode):
print "foo"
#判断对象是否是basestring对象
if isinstance(u'', basestring):
print u''

'''调用chr()、unichr()、ord()函数'''
#调用chr()、unichr()获取字符和unicode字符
try:
print chr(65)
print unichr(12345)
print chr(267)
print unichr(1114113)
except ValueError,v:
print v

#获取ASCII数值或者Unicode数值
try:
print ord("a")
print ord("*")
print ord(u'\ufffff')
except TypeError,t:
print t

#调用函数
callBuildInFunc()


举报

相关推荐

0 条评论