Is there a way to split a string into 2 equal halves without using a loop in Python?
6 Answers
Python 2:
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]
Python 3:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
-
4Or even
firstpart, secondpart = string[::2], string[1::2]
since the question didn't specify that the parts had to be contiguous.– DuncanJan 25, 2011 at 9:16 -
23In python3 :
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
– ucharJul 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
-
-
splice indeces must be int, firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string))/2:] Aug 26, 2019 at 8:58
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:]
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')
-
Thanks. I was looking for this. No one has addressed the odd length of the string. Jun 15 at 6:33
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):]
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):]