How to Split a String in Half in Python?

Ways to Divide a String in Half in Python

This tutorial will show how to split a string in half in Python. To achieve this, we will use the string-slicing method.

To split a string in half in Python.

  1. Use the len() function to find the length of the string.
  2. Split it in half using this length with string slicing.
# Split a string in half in Python
string = "educate&python"
string1 = string[len(string)//2:]
string2 = string[:len(string)//2]
print(string2, string1)
# Output: educate &python    

In the above example, we use the len() function to return the length of the string and divide it in half using the // operator. We use this value with string slicing to divide the string in half.

The // operator performs floor division and returns an integer, discarding any decimal part.

Now the above example deals with a string with even characters. What if the total characters are odd?

In such a case, it’s obvious one part will have an extra character. We can deal with this character and remove it from the resulting half using a simple if statement.

See the code below.

# Split a string in half in Python
string = "educatepython"
string2 = string[:len(string)//2]
string1 = string[len(string)//2 if len(string)%2 == 0
                 else (((len(string)//2))+1):]
print(string2, string1)
# Output: educat python    

In the above example, we check if the string has an even or odd number of characters and trim off the extra character if the length is odd.

To conclude

In this article, we concluded how to split a string in half in Python. We demonstrate the use of the string-slicing technique to achieve this. Two cases were shown, first, where the length of the string is even, and second, where the length is odd.

Fun Fact: A string is actually a variable in Python! Know How to check if a variable is a string in python 

Explore more from this category at Python Strings. Alternatively, search and view other topics at All Tutorials.