切字符串

| No Comments | No TrackBacks
有个同事问python里怎么把字符串按每两个切成一个列表。给了个答案
def splitByNumber(s,n):
    for i in range(0,len(s),n):
        yield s[i:i+n]
用匿名函数可以写成一句话
splitByNumber = lambda s,n: map(lambda x: s[x:x+n],range(0,len(s),n))
结果如下
splitByNumber('fuckgfw',2)
['fu', 'ck', 'gf', 'w']
splitByNumber('fuckgfw',3)
['fuc', 'kgf', 'w']

No TrackBacks

TrackBack URL: http://mt.khsing.net/cgi-bin/mt-tb.cgi/86

Leave a comment

About this Entry

This page contains a single entry by Guixing published on July 22, 2009 6:05 AM.

python-ldap与python25以及CentOS 4.x was the previous entry in this blog.

父母在,不远游 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.