Python里怎么按数切字符串

有个同事问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']

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.