Py&禅

博客园 首页 新随笔 联系 订阅 管理

2010年6月5日 #

摘要: Problem:如题Solution:一个简单的工厂类方法:import stringdef 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... 阅读全文
posted @ 2010-06-05 11:33 Py&禅 阅读(262) 评论(0) 推荐(0)

2010年6月1日 #

摘要: Problem:检查字符串中是否存在某些字符的集合Solution:下面的方法可以用在任何的序列容器中def containsAny(seq, aset): """ Check whether sequence seq contains ANY of the items in aset. """ for c in seq: if c in aset: return True return Fals... 阅读全文
posted @ 2010-06-01 13:04 Py&禅 阅读(222) 评论(0) 推荐(0)

摘要: # -*- coding:utf-8 -*-"""Created on 2010-5-21单链表的实现 1@author: Administrator"""class LinkedList(object): class Element(object): ''' 定义元素,包含了数据内容_datum和指向下一元素的链接_next ''' def __init__(self,list,datum... 阅读全文
posted @ 2010-06-01 05:37 Py&禅 阅读(336) 评论(0) 推荐(0)

2010年5月31日 #

摘要: Problem:You want to reverse the characters or words in a string.Solution:使用字符串的切片操作 [start: stop : step], 当 step为-1时,可实现字符反转操作revchars = astring [::-1]为了实现words的反转,需要建立一个列表来保存words,astring = 'hello wo... 阅读全文
posted @ 2010-05-31 12:43 Py&禅 阅读(246) 评论(0) 推荐(0)

摘要: Problem:将若干个字符串合并到一起Solution:使用 ''.join()来实现对字符串列表的合并。(效率较高)largestring = ''.join(smallpieces)使用%格式符号largeString = '%s%s something %s yet more' % (small1, small2, small3)或使用 reduce()import operatorlar... 阅读全文
posted @ 2010-05-31 07:18 Py&禅 阅读(141) 评论(0) 推荐(0)

2010年5月30日 #

摘要: Problem:Solution:使用lstrip, rstrip, strip方法。>>> x = ' hej '>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'| hej | hej | hej |Discussion:也可以指定要去除的元素,而不单单限于空白>>... 阅读全文
posted @ 2010-05-30 10:40 Py&禅 阅读(147) 评论(0) 推荐(0)

摘要: Problem:Solution:使用ljust(), rjust(), center(),来调整字符串对象的位置>>> print '|', 'hej'.ljust(20), '|', 'hej'.rjust(20), '|', 'hej'.center(20), '|'| hej | hej | hej |使用ljust, rjust, center內建函数的第二个叁数来对空... 阅读全文
posted @ 2010-05-30 10:08 Py&禅 阅读(90) 评论(0) 推荐(0)

摘要: Problem如题Solution最简单直接的方法是使用isinstance()和basestring来判断对象是否为basestring.basestring is a common base class for the str and unicode types.def isAstring(anobj): return isinstance(anobj, basestring)注意该函数不能支... 阅读全文
posted @ 2010-05-30 10:06 Py&禅 阅读(158) 评论(0) 推荐(0)

摘要: Problem:如题Solution:ord( ) 由一个ascii字符返回对应的整型数字chr( i) 由一个数字整型 i 返回一个ascii字符 ord( ) unicode -> 数字unichr( ) 数字 -》 unicodeDiscussion:转换字符串成一个字符值的列表,print map(ord, 'ciao')>>> [99, 105, 97, 111]... 阅读全文
posted @ 2010-05-30 10:04 Py&禅 阅读(810) 评论(0) 推荐(0)

摘要: problem:处理sting,一次一个字符Solution:使用list()內建函数,将字符串转换为一个包含单个字符的列表thestring = "hello world"thelist = list(thestring)三种遍历的方法:for c in thestring: do_something_with(c)result = [do_something_with(c) for c in ... 阅读全文
posted @ 2010-05-30 10:00 Py&禅 阅读(244) 评论(0) 推荐(0)