python 中实现按照指定步长拆分字符串
作者:互联网
001、
>>> import re >>> str = "sefderfhjuynb" >>> re.findall(".{3}", str) ## 步长为3 ['sef', 'der', 'fhj', 'uyn'] >>> re.findall(".{2}", str) ## 步长为2 ['se', 'fd', 'er', 'fh', 'ju', 'yn']
不能整除?:
>>> str 'sefderfhjuynb' >>> remainder = len(str) % 3 >>> remainder 1 >>> result = re.findall(".{3}", str) >>> result ['sef', 'der', 'fhj', 'uyn'] >>> result.extend(list(str[-remainder:])) >>> result ['sef', 'der', 'fhj', 'uyn', 'b']
002、
(base) root@PC1:/home/test2# ls test.py (base) root@PC1:/home/test2# cat test.py ## 测试程序 #!/usr/bin/python str = 'sefderfhjuynb' steps = len(str) // 3 remainder = len(str) % 3 start = 0 end = 3 result = [] for i in range(steps): result.append(str[start:end]) start += 3 end += 3 if remainder != 0: result.append(str[-remainder:]) print(result) (base) root@PC1:/home/test2# python test.py ## 运行结果 ['sef', 'der', 'fhj', 'uyn', 'b']
标签:拆分,sef,python,##,步长,result,str,re,remainder 来源: https://www.cnblogs.com/liujiaxin2018/p/16580770.html