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) [email protected]:/home/test2# ls test.py (base) [email protected]:/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) [email protected]:/home/test2# python test.py ## 运行结果 ['sef', 'der', 'fhj', 'uyn', 'b']
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280090.html