Skip to Main Content
Blog

Split String by Size in Python

Split String by Size in Python

import math


def main():
	txt = input("Enter string: ")
	size = int(input("Enter packet size: "))

	for s in split(txt, size):
		print(s)


def split(txt: str, size: int):
	if size == 0:
		raise ValueError("Packet size must be greater than zero.")

	chunks_count = math.ceil(len(txt) / size)
	chunks = []

	beg = 0
	while beg < len(txt):
		end = min(len(txt), beg + size)
		chunks.append(txt[beg:end])
		beg += size

	return chunks


if __name__ == "__main__":
	main()