Is there a way to split a string into 2 equal halves without using a loop in Python? Show asked Jan 25, 2011 at 3:04
Python 2:
Python 3:
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
answered Jan 25, 2011 at 3:09
lallilalli 5,9037 gold badges41 silver badges55 bronze badges Whoever is suggesting This works perfectly. Verified on edx.
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).
answered Feb 24, 2017 at 13:03
In Python 3:
answered Jan 26, 2018 at 16:39
minor correction the above solution for below string will throw an error
you can do an
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: How do you split a string into two in Python?Python String split() Method
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
How do you split a string into two parts?Algorithm. STEP 1: START.. STEP 2: DEFINE str = "aaaabbbbcccc". STEP 3: DEFINE len.. STEP 4: SET n =3.. STEP 5: SET temp = 0.. STEP 6: chars = len/n.. STEP 7: DEFINE String[] equalstr.. STEP 8: IF (len%n!=0) then PRINT ("String can't be divided into equal parts") else go to STEP 9.. How do you split a string into equal parts in Python?Python. str = "aaaabbbbcccc";. #Stores the length of the string.. length = len(str);. #n determines the variable that divide the string in 'n' equal parts.. n = 3;. temp = 0;. chars = int(length/n);. #Stores the array of string.. |