34
votes

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

6

6 Answers

62
votes
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
6
votes
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
2
votes

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:]
1
votes

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')
1
votes

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):]
0
votes

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):]