56

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

6 Answers 6

89

Python 2:

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

Python 3:

firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
Sign up to request clarification or add additional context in comments.

5 Comments

Or even firstpart, secondpart = string[::2], string[1::2] since the question didn't specify that the parts had to be contiguous.
In python3 : firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
little confusing this answer as string stands usually for a keyword - but here the variable is ment ...
@Dominik string isn't a keyword, though it is a module, if that's what you're thinking of.
splice indeces must be int, firstpart, secondpart = string[:int(len(string)/2)], string[int(len(string))/2:]
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:]

Comments

7
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]

Comments

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 Comment

Thanks. I was looking for this. No one has addressed the odd length of the string.
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):]

Comments

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 Comment

you should use // instead of / for division.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.