You are being very, very specific in what you are trying to do. If this is an exercise that you are trying to do, in which the instructions are, "Given a 5 character string, create a new string where the first two characters alternate with the last 3 in a new string" then the code above will work for you in this limited case.
If you are trying to solve a problem, however, it would be helpful to have more details about the problem you are trying to solve and why you want to solve it.
As en_Knight points out, this function does not work on a variety of inputs. And the point in computing, generally, is to create code that makes tasks easier by being general enough to solve the same problems many times with different inputs.
A few style notes: when getting sections of lists, you only need to provide the starting number when it is not 0, or the ending number when it is not through the end of the list. So instead of
second_part = formula[3:len(formula_chosen)]
you can simply write:
second_part = formula[3:]
where the empty part after :
signals "Get all content to the end of the string".
To give you an idea of what I mean by writing code so it is a more general solution, here is a function that does what you describe on strings of any length: dividing them exactly in half and then alternating the characters.
def alternate_half(input):
output = ""
input_a = input[:len(input)/2]
input_b = input[len(input)/2:]
for pos, char in enumerate(input_b):
output += char
if len(input_a) > pos:
output += input_a[pos]
return output
Explained:
- def just sets up the function, named alternate_half, here with a parameter, or input value, called "input" that is the string you have labeled as formula above.
input[:len(input)/2]``input[len(input)/2:]
- these are both just slices of the main list. It uses the trick above — that python automatically fills in 0 or the end of the list. It also uses the trick that when dividing by integers in Python, you get an integer in return. So for example in the case of a 5 length string, len(input)/2
is 2, so input_a is the first 2 characters, and input_b is the characters 2 through the end of the string, so "123".
- enumerate returns a counter for each item in an iterable (such as a string). So
enumerate("*+123")
is functionally equivalent to [(0, '*'), (1, '+'), (2, '1'), (3, '2'), (4, '3')]
. So we can use the positional argument in input_a
and append to the corresponding character in input_b
.
- Finally we just check to make sure that if input_a is shorter, we don't try to get a character past the length of the string. Because we're dividing the strings in half,
input_a
will never be more than one character shorter than input_b.