Python – Split string in half

Python – Split string in half

To split a given string into two equal halves in Python, you can use string slicing technique.

If given string is

"HelloWorld"

Then splitting this string in half means

"Hello"   ← First half
"World"   ← Second half

In this tutorial, we shall go through a step by step process of using string slicing technique to split a given string into two halves of equal lengths, through an example.

1. Split string in half using string slicing technique in Python

Consider that we are given a string in x, and we have to split this string in half, i.e., two equal length halves.

Steps

  1. Given a string in x.
x = "HelloWorld"
  1. Find the mid point of the string. We shall use this value as index to slice the string into two halves.
midpoint = len(x) // 2

Please note that we are using Python floor division operator // in the above expression.

  1. To find the first half of the string x, use the following slice expression. This expression returns the first half that spans from the starting to midpoint of the given string x.
x[:midpoint]
  1. To find the second half of the string x, use the following slice expression. This expression returns the second half that spans from midpoint to end of given string x.
x[midpoint:]

Program

The complete program to split the given string into two equal length halves using string slicing technique.

Python Program

# Input string
x = "HelloWorld"

# Calculate the midpoint index
midpoint = len(x) // 2

# Split the string into two halves
first_half = x[:midpoint]
second_half = x[midpoint:]

# Print the results
print(f"First half  : {first_half}")
print(f"Second half : {second_half}")
Run Code Copy

Output

First half  : Hello
Second half : World

You have to remember that the first half and second half would be equal in length if the length of the given string is even.

If the length of the given string is odd, then the second half would have one character more than the first half, because of the floor division we are doing on the string length.

Python Program

# Input string (odd length of 11)
x = "HelloWorldy"

# Calculate the midpoint index
midpoint = len(x) // 2

# Split the string into two halves
first_half = x[:midpoint]
second_half = x[midpoint:]

# Print the results
print(f"First half  : {first_half}")
print(f"Second half : {second_half}")
Run Code Copy

Output

First half  : Hello
Second half : Worldy

Summary

In this tutorial, we learned how to split a given string in half using string slicing technique. We have gone through an example program with detailed steps.

Related Tutorials

Code copied to clipboard successfully 👍