# Python | Split String in Half

Rate this post

🍎Summary: The easiest method to split a string in half is to slice the string mid-way using its mid index, which can be calculated as len(text)//2. There are numerous other ways of solving the problem, which have been discussed below.

### Minimal Example

text = "abc xyz"

# Method 1
first_part, second_part = text[:len(text)//2], text[len(text)//2:]
print("First Half: ", first_part)
print("Second Half: ", second_part)

# Method 2
half, rem = divmod(len(text), 2)
print("First Half: ", text[:half + rem])
print("Second Half: ", text[half + rem:])

# Method 3
li = text.split()
n = len(li)//2
res = [" ".join(li[x:x+n]) for x in range(0, len(li), n)]
print("First Half: ", res[0])
print("Second Half: ", res[1])

# Method 4
from itertools import accumulate
li = text.split()
len_split = [len(li)//2]*2
results = [li[x - y: x] for x, y in zip(accumulate(len_split), len_split)]
print("First Half: ", " ".join(results[0]))
print("Second Half: ", " ".join(results[1]))

# Outputs:
# First Half:  abc
# Second Half: xyz

## Problem Formulation

Problem: Given a string. How will you split the string in exactly two halves?

## Example

Given below is a string containing ten substrings. You have to split it into two halves such that each half contains exactly five words.

# Input
text = "Sun rises in the east and sets in the west"
# Expected Output
First Half:  Sun rises in the east
Second Half:  and sets in the west

Without further ado, let’s dive into the solutions.

## Method 1: Use Slicing

Approach: One way to split the string into two halves is to slice it using its mid index. The mid index can be calculated as len(text)//2. Once you have the mid index, the first half can be extracted by slicing the string from the start till the mid index. While the Second half can be extracted by slicing the string from the mid index till the end.

Code:

text = "Sun rises in the east and sets in the west"
first_part, second_part = text[:len(text)//2], text[len(text)//2:]
print("First Half: ", first_part)
print("Second Half: ", second_part)

Output:

First Half:  Sun rises in the east
Second Half:  and sets in the west

Trivia: Slicing is a concept to carve out a substring from a given string. Use slicing notation s[start:stop:step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start=0stop=len(lst)step=1). For example, the expression s[2:4] from string 'hello' carves out the slice 'll' and the expression s[:3:2] carves out the slice 'hl'.

🌟Related Read: Introduction to Slicing in Python

## Method 2: Using divmod

Prerequisite: Python’s built-in divmod(a, b) function takes two integer or float numbers a and b as input arguments and returns a tuple (a // b, a % b). The first tuple value is the result of the integer division a//b. The second tuple is the result of the remainder, also called modulo operation a % b. In case of float inputs, divmod() still returns the division without remainder by rounding down to the next round number.

The idea here is exactly the same as the one used previously. The only difference here is – we are using the divmod method to find out the mid index of the string which can be used to slice it into two halves.

Code:

text = "Sun rises in the east and sets in the west"
half, rem = divmod(len(text), 2)
print("First Half: ", text[:half + rem])
print("Second Half: ", text[half + rem:])

Output:

First Half:  Sun rises in the east
Second Half:  and sets in the west

## Method 3: Split and Use List Comprehension

Approach: Slice the string to create a split list of substrings. Since the words are separated by a space in our case, so we can simply split the string without passing any separator, as the string will be split at the occurrence of any whitespace character.

Once you have the list, use a list comprehension to iterate through the length of the string such that the step size of the iteration is equal to half the length of the string. This allows you to break the list into two equal parts. You can then join each item of each part of the list using the join method.

Code:

text = "Sun rises in the east and sets in the west"
li = text.split()
n = len(li)//2
res = [" ".join(li[x:x+n]) for x in range(0, len(li), n)]
print("First Half: ", res[0])
print("Second Half: ", res[1])

Output:

First Half:  Sun rises in the east
Second Half:  and sets in the west

Trivia: str.join(iterable) concatenates the elements in an iterable. The result is a string, whereas each element in the iterable are “glued together” using the string on which it is called as a delimiter.

## Method 4: Using accumulate

Another way to solve the given problem is to use the accumulate() function from the itertools module.

Code:

from itertools import accumulate

text = "Sun rises in the east and sets in the west"
len_split = [len(li)//2]*2
results = [li[x - y: x] for x, y in zip(accumulate(len_split), len_split)]
print("First Half: ", " ".join(results[0]))
print("Second Half: ", " ".join(results[1]))

Output:

First Half:  Sun rises in the east
Second Half:  and sets in the west

Explanation: The above code imports the itertools library to call in and use the accumulate() function. Split the string using the split function, which creates a list containing split substrings. Use this list and calculate the mid index and multiply the deduced outcome from the list twice as [len(li)//2]*2. Finally, use a list comprehension that uses the zip and accumulate methods to iterate through the list containing the split substrings and split the list into two (2) based on the computation performed previously.

## Conclusion

Phew! We have learned as many as four different ways to split a string in half. Feel free to use the method that suits your needs. I hope this tutorial added some value to your coding journey. Please subscribe and stay tuned for more interesting reads and discussions.