Split a string into 2 in Python

Question:

Is there a way to split a string into 2 equal halves without using a loop in Python?

Asked By: Kiwie Teoh

||

Answers:

firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
Answered By: Senthil Kumaran
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
Answered By: lalli

Another possible approach is to use divmod. rem is used to append the middle character to the front (if odd).

def split(s):
    half, rem = divmod(len(s), 2)
    return s[:half + rem], s[half + rem:]

frontA, backA = split('abcde')
Answered By: J. Lernou

In Python 3:
If you want something like
madam => ma d am
maam => ma am

first_half  = s[0:len(s)//2]
second_half = s[len(s)//2 if len(s)%2 == 0 else ((len(s)//2)+1):]
Answered By: tHappy

minor correction
the above solution for below string will throw an error

string = '1116833058840293381'
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]

you can do an int(len(string)/2) to get the correct answer.

firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string)/2):]

Answered By: som shubham sahoo

Whoever is suggesting string[:len(string)/2], string[len(string)/2] is not keeping odd length strings in mind!

This works perfectly. Verified on edx.

first_half  = s[:len(s)//2]
second_half = s[len(s)//2:]
Answered By: Neha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.