Python
共 9 篇文章
Python菜谱-简化String的translate方法
你经常需要使用到字符串的translate方法,但是发现真的很难记住这个函数的使用细节以及string.maketrans的使用。因此,你需要一个简化使用translate的方法 import string def translator(frm='', to='', delete='', keep=None): if len(to)==1: to=to*len(frm) trans=string.maketrans(frm,to) if keep is not none: allchars=string.maketrans('', '') delete = allchars.translat…
2010-02-26 11:06 · Python
Python菜谱-检查一集合的字符是否存在于一个字符串中
要得知一个集合的字符是否存在于一个字符串中 最简单的方法如下,这个方法是通用的,不仅仅是一个Set的字符也可以是list,字符串也可以是任意的序列,如元组,列表。 def containsAny(seq, aset): for c in seq: if c in aset: return True return False
2010-02-26 10:40 · Python
Python菜谱-反转字符串中的字符或单词
你希望反转字符串中的字符或单词 String本身是不可变的,因此,要反转,必须重新创建一个拷贝。反转字符如下 revchars = astring[::-1] 为了反转单词,你需要创建一个单词的list。然后反转它,以及再连接为字符串。 revwords = astring.split( ) #字符串-》LIST revwords.reverse( ) # 反转LIST revwords = ' '.join(revwords) #LIST-》字符串 当然也可以一个语句来实现 revwords = ' '.join(astring.split( )[::-1]) 如果要保留中间的空白字符,可…
2010-02-26 10:24 · Python
Python菜谱-连接字符串
经常需要把几个字符串进行连接。 1.使用join方法。 largeString = ''.join(pieces) 2.用格式化字符串的方法。 largeString = '%s%s something %s yet more' % (small1, small2, small3)
2010-02-14 13:09 · Python
Python菜谱-字符串去除空格
一般来说,字符串处理都需要空格 有三个方法处理来处理字符串,lstrip,rstrip,strip。 x = ' hej ' print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|' | hej | hej | hej |
2010-02-14 12:52 · Python
Python菜谱-对齐字符串
编程中经常需要对齐字符串:left,right,center print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|' | hej | hej | hej |
2010-02-14 12:30 · Python
Python菜谱-测试一个对象是否是字符串
要判断一个对象是否是字符串可以使用如下方法 def isAsString(anobj) return isinstance(anobj,basestring)
2010-02-14 12:22 · Python
Python菜谱-字符和数字码的转换
字符和ASCII或Unicode码的转换 1.可以使用ord和chr内置函数 print ord('a') 97 print chr(97) a 2.ord也支持Unicode码。反之使用unichr print ord(u'\u2020') 8224 print repr(unichr(8224)) u'\u2020'
2010-02-13 16:54 · Python
Python菜谱-逐一处理字符串中的字符
1.把字符串转为list str="fengxuelianyi" strList=list(str) 2.不需要创建list,可以直接使用for循环 for c in thestring: do_something_with(c) 3.也可以使用for子句 results = [do_something_with(c) for c in thestring] 4.也可以使用map函数 results = map(do_something, thestring)
2010-02-13 16:39 · Python