Is there a way to split a string into 2 equal halves without using a loop in Python?
asked Jan 25, 2011 at 3:04
Python 2:
firstpart, secondpart = string[:len(string)/2], string[len(string)/2:]Python 3:
firstpart, secondpart = string[:len(string)//2], string[len(string)//2:]
zamarov
1672 silver badges16 bronze badges
answered Jan 25, 2011 at 3:07
Senthil KumaranSenthil Kumaran
52.4k14 gold badges90 silver badges127 bronze badges
5
a,b = given_str[:len(given_str)/2], given_str[len(given_str)/2:]
answered Jan 25, 2011 at 3:09
lallilalli
5,9037 gold badges41 silver badges55 bronze badges
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:]
token
8431 gold badge8 silver badges22 bronze badges
answered Aug 27, 2020 at 23:56
NehaNeha
511 silver badge1 bronze badge
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')answered Feb 24, 2017 at 13:03
In Python 3:
If you want something like
madam => ma d am
maam => ma am
answered Jan 26, 2018 at 16:39
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):]
SuperKogito
2,8753 gold badges14 silver badges35 bronze badges
answered Apr 14, 2019 at 20:40
To split a provided string into two halves using Python 3. We have many ways to split a provided python string into two halves. Let’s go through the methods with examples to achieve them in this post. We can use the len() method and get half of the string. We then use the slice
notation technique to slice off the first and second of the string value to store the then in separate variables. Code: Output: We can use an if condition to check if the index value is less than half of the string length -1. So by looping to string index values, we can get two split half of the string value. Code: Output:Problem
Solution
Using slice notation method:
Using for loop method: