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:]
5 Comments
Duncan
Or even
firstpart, secondpart = string[::2], string[1::2] since the question didn't specify that the parts had to be contiguous.uchar
In python3 :
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]Dominik Lemberger
little confusing this answer as string stands usually for a keyword - but here the variable is ment ...
Shankara Narayana
splice indeces must be int, firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string))/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')
1 Comment
Manoj Kumar
Thanks. I was looking for this. No one has addressed the odd length of the string.
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 Comment
AhmedO
you should use
// instead of / for division.