How to split a string into two halves in Python?

Problem

To split a provided string into two halves using Python 3.

Solution

We have many ways to split a provided python string into two halves. Let’s go through the methods with examples to achieve them in this post.

Using slice notation method:

We can use the len() method and get half of the string. We then use the slice notation technique to slice off the first and second of the string value to store the then in separate variables.

Code:

def splitstring(value):
    string1, string2 = value[:len(value)//2], value[len(value)//2:]
    return string1, string2
mystring = 'SplitWords'
print('My string',mystring)
print('Split the string into two:',splitstring(mystring))

Output:

My string: SplitWords
Split the string into two: ('Split', 'Words')

Using for loop method:

We can use an if condition to check if the index value is less than half of the string length -1. So by looping to string index values, we can get two split half of the string value.

Code:

def splitstring(value):
    string1 = ''
    string2 = ''
    for i in range(0,len(value)):
        if i <= len(value)//2-1:
            string1 = string1 + value[i]
        else:
            string2 = string2 + value[i]
    return string1, string2
mystring = 'SplitWords'
print('My string',mystring)
print('Split the string into two:',splitstring(mystring))

Output:

My string SplitWords
Split the string into two: ('Split', 'Words')