Python - Split string into N equal parts
Python - Split string into N equal parts
To split a given string into N equal parts in Python, you can use a For loop with range from zero up to length of the string in steps of each part length, and use string slicing to find the respective part.
If given string is
"abcdefghijklmno"
then splitting this string into 5 equal parts means
"abc" ← 1st part
"def" ← 2nd part
"ghi" ← 3rd part
"jkl" ← 4th part
"mno" ← 5th part
In this tutorial, we shall go through a step by step process of using a For loop and string slicing technique to split a given string into N equal parts, through an example.
1. Split string into N equal parts using For loop and string slicing technique in Python
Consider that we are given a string in x, and we have to split this string into N equal parts, i.e., N parts with equal lengths.
Steps
- Given a string in x.
x = "abcdefghijklmno"
- Given N value.
N = 5
- Use a Python For loop with range, where the range starts from 0 and stops at length of the string in steps of N, and during each ith iteration, find the ith part in the string using string slicing.
for i in range(0, len(x), part_size):
part = x[i:i+part_size]
- You may create an empty list, say parts, to store each of the part found inside the For loop.
Program
The complete program to split the given string into N equal parts using a For loop and string slicing.
Python Program
def split_string(x, N):
# Calculate the length of each part
part_size = len(x) // N
# Initialize a list to store the parts
parts = []
# Iterate through the string and split it into equal parts
for i in range(0, len(x), part_size):
part = x[i:i+part_size]
parts.append(part)
return parts
# Input string
x = "abcdefghijklmno"
# Number of parts to split the string into
N = 5
# Split the string into N equal parts
result = split_string(x, N)
# Print the results
for i, part in enumerate(result):
print(f"Part {i+1}: {part}")
Output
Part 1: abc
Part 2: def
Part 3: ghi
Part 4: jkl
Part 5: mno
Summary
In this tutorial, we learned how to split a given string into N equal parts using a For loop and slicing technique. We have gone through an example program with detailed steps.