首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

字符串按每三个字符分割

2012-12-21 
字符串按每3个字符分割# encoding: utf-8有字符串 XXXxxxXXXxxxXXXxxxXXXxxxXXX, 要求把该字符串按每

字符串按每3个字符分割

# encoding: utf-8'''有字符串 'XXXxxxXXXxxxXXXxxxXXXxxxXXX', 要求把该字符串按每3个字符分割, 返回一个列表。'''import res = 'XXXxxxXXXxxxXXXxxxXXXxxxXXX'def slice_string_1(org_str, step):    # 实现1    return [org_str[i: i+step] for i in xrange(0, len(org_str), step)]def slice_string_2(org_str, step):    # 实现2    return re.findall('.{%s}' % step, org_str)if __name__ == '__main__':   '''   result:   ['XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX']   ['XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX', 'xxx', 'XXX']   '''   step = 3   print slice_string_1(s, step)   print slice_string_2(s, step)
?

热点排行