您的位置:首页 > 编程语言 > Python开发

字符串常用操作

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']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string python