
Python
xiayuanfeng
这个作者很懒,什么都没留下…
展开
-
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 thestri...原创 2010-02-13 16:39:50 · 125 阅读 · 0 评论 -
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:53 · 125 阅读 · 0 评论 -
Python菜谱-测试一个对象是否是字符串
要判断一个对象是否是字符串可以使用如下方法 def isAsString(anobj) return isinstance(anobj,basestring)原创 2010-02-14 12:22:45 · 114 阅读 · 0 评论 -
Python菜谱-对齐字符串
编程中经常需要对齐字符串:left,right,center print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|' | hej | hej | hej | ...原创 2010-02-14 12:30:41 · 124 阅读 · 0 评论 -
Python菜谱-字符串去除空格
一般来说,字符串处理都需要空格 有三个方法处理来处理字符串,lstrip,rstrip,strip。 x = ' hej ' print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|' | hej | hej | hej | ...原创 2010-02-14 12:52:35 · 99 阅读 · 0 评论 -
Python菜谱-连接字符串
经常需要把几个字符串进行连接。 1.使用join方法。 largeString = ''.join(pieces) 2.用格式化字符串的方法。 largeString = '%s%s something %s yet more' % (small1, small2, small3) ...原创 2010-02-14 13:09:50 · 113 阅读 · 0 评论 -
Python菜谱-反转字符串中的字符或单词
你希望反转字符串中的字符或单词 String本身是不可变的,因此,要反转,必须重新创建一个拷贝。反转字符如下 revchars = astring[::-1] 为了反转单词,你需要创建一个单词的list。然后反转它,以及再连接为字符串。 revwords = astring.split( ) #字符串-》LIST revwords.reve...2010-02-26 10:24:16 · 127 阅读 · 0 评论 -
Python菜谱-检查一集合的字符是否存在于一个字符串中
要得知一个集合的字符是否存在于一个字符串中 最简单的方法如下,这个方法是通用的,不仅仅是一个Set的字符也可以是list,字符串也可以是任意的序列,如元组,列表。 def containsAny(seq, aset): for c in seq: if c in aset: return True return False ...原创 2010-02-26 10:40:23 · 203 阅读 · 0 评论 -
Python菜谱-简化String的translate方法
你经常需要使用到字符串的translate方法,但是发现真的很难记住这个函数的使用细节以及string.maketrans的使用。因此,你需要一个简化使用translate的方法 import string def translator(frm='', to='', delete='', keep=None): if len(to)==1: to=to*le...2010-02-26 11:06:43 · 123 阅读 · 0 评论