字符串常用操作
2015-08-17 00:28
615 查看
#-*-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=",i help(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 += s1 print "largeString=",largeString print "source string =%s,%f" % ("Hello,python ",1.0003) help(str.join)
"""使用格式化字符串合并字符串是最优的选择""" name = 'Zroad' number = 100 print "Hello,%s;Go and %d" %(name,number)
5、反转字符串的简单实现方法:
chars = 'ZroadYH' revchars = chars[::-1] print "revchars = %s" % revchars words = "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 False print 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=",allchars def makefilter(keep): """ 返回一个函数,此函数接受keep参数,返回一个字符拷贝,仅包含keep中的字符串 """ delchars = allchars.translate(allchars,keep) def thefilter(s): #闭包函数的定义 return s.translate(allchars,delchars) return thefilter if __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,world print 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']
相关文章推荐
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- android上改变listView的选中颜色
- String.intern