字符串常用操作

来源:互联网 发布:linux 升级内核好处 编辑:程序博客网 时间:2024/06/11 20:44
#-*-coding:utf-8-*-import string

1、判断str/Unicode字符串对象

def isAString(anobj):    return isinstance(anobj,basestring) #basesting是str,unicode的父类def isAInt(anobj):    '''<type str><type str><type 'float'><type 'int'><type 'list'><type 'dict'><type 'tuple'><type 'set'><type 'file'>    '''    return isinstance(anobj,int)for i in [1,1.1,True,0,3e-1,4e2]:    if isAInt(i):        print " A int!"    else:        print "Not a int!"    print "i=",ihelp(basestring)help(isinstance)help(type)print type('a')print type("好的")print type(1.2)print type(1)print type([1,2,3])print type({'a':1})print type((1,23))print type({1,2})f = open("a.txt",'r')print type(f)f.close()print isAString('Hello,pyton')print isAString(u'\8338')print isAString(3990)print isAString(chr(58))

2、字符串左、中、右对齐

print "|",'hello,python'.rjust(20,'+') #width参数表示长度,包括对齐的字符串+间隔字符print '|','hello,python'.ljust(20,'*') #左对齐,不足宽度的字符以'*'填充print '|','hello,python1'.center(20,'-') #不加第二个参数默认添加空格s = "Hello,python"print s.title()print dir(str)help(str.title)help(s.rjust)

3、去除字符串两端空格

x = "    hello,python   "print x.lstrip()+'here'print x.strip()print x.rstrip()y = "here,  hello,python,   here"print y.strip('hre')  #去除字符串y左右两边的'h'/'r'/'e'字符

4、字符串合并

strs = ['hello',',','python']print '/'.join(strs)  #join函数接受字符串列表参数largeString = ''for s1 in strs:    largeString += s1print "largeString=",largeStringprint "source string =%s,%f" % ("Hello,python ",1.0003)help(str.join)
"""使用格式化字符串合并字符串是最优的选择"""name = 'Zroad'number = 100print "Hello,%s;Go and %d" %(name,number)

5、反转字符串的简单实现方法:

chars = 'ZroadYH'revchars = chars[::-1]print "revchars = %s" % revcharswords = "This is a very good boy !"print "words.splite()=" , words.split()print " ".join(words.split()[::-1])

6、检查字符串中是否包含某字符集合中的字符

def containsAny(seq,aset):    """    检查序列seq中是否包含sset中的项    """    for c in seq:        if c in aset:            return True    return Falseprint containsAny("abc","World,ello")print containsAny(['1','2','3','a','b','c'],['11','b'])help(str.translate)

7、str.maketrans/str.translate的使用

"""替换、删除字符串中的指定字符"""table = string.maketrans('12','@*')  #将字符串中的字符'1','2'替换为'@','@'print "adbd1kekk32#".translate(table,'ka') #param(table,deletechars)

8、过滤字符串中不属于指定集合的字符

"""使用到闭包函数,需要关注"""allchars = string.maketrans("", "") #定义translate翻译表print "allchars=",allcharsdef makefilter(keep):    """    返回一个函数,此函数接受keep参数,返回一个字符拷贝,仅包含keep中的字符串    """    delchars = allchars.translate(allchars,keep)    def thefilter(s):  #闭包函数的定义        return s.translate(allchars,delchars)    return thefilterif __name__ == "__main__":    filter1 = makefilter("obcd")    print "The result=" , filter1("Hello,python!aaa,bbb,ccc,ddd")

9、字符串的大小写控制

srcChar = "aBc,hEllo,World"print srcChar.upper()print srcChar.lower()print srcChar.capitalize()  #Abc,hello,worldprint srcChar.title() #Abc,Hello,World

10、其他操作

import sys#将字符串转换为序列strList = list("Hello,python!")print strList#遍历字符串中的任意一字符for char in "Hello,python!":    #print char    #print char,  #print不换行的处理    sys.stdout.write(char)    sys.stdout.flush()print '\n'#输出字符串不换行的第二种处理sys.stdout.write("Hello,world!")sys.stdout.flush()#使用map函数遍历字符串中的每个字符results = map(ord,"hello,python")print results#ASC||/Unicode单字符串与码值转换print ord('a')  #ASC||字符串 ‘a’对应的码值print chr(97)   #ASC||码97对应的字符#str()与repr()的区别,str函数针对的是ASC||码print ord(u'\u2020')  #Unicode字符\u2020对应的码值print repr(unichr(8224)) #将unicode码值转换为Unicode字符 #将字符串转换为列表file = "c:/workspace/test/python/hello.py"lDir = file.split('/')print "lDir=", lDir #lDir= ['c:', 'workspace', 'test', 'python', 'hello.py'] 
0 0
原创粉丝点击