54

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

6 Answers 6

84

Python 2:

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

Python 3:

firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
5
  • 4
    Or even firstpart, secondpart = string[::2], string[1::2] since the question didn't specify that the parts had to be contiguous.
    – Duncan
    Jan 25, 2011 at 9:16
  • 23
    In python3 : firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
    – uchar
    Jul 11, 2014 at 13:27
  • little confusing this answer as string stands usually for a keyword - but here the variable is ment ... Jul 23, 2018 at 5:05
  • @Dominik string isn't a keyword, though it is a module, if that's what you're thinking of.
    – wjandrea
    May 31, 2019 at 13:55
  • splice indeces must be int, firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string))/2:] Aug 26, 2019 at 8:58
10

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:]
7
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
4

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
  • Thanks. I was looking for this. No one has addressed the odd length of the string. Jun 15 at 6:33
1

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

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

1
  • you should use // instead of / for division.
    – AhmedO
    Dec 3, 2022 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.