Ok so what im trying to do is to alternate the first two values in the string in the rest of the string.
what i have is..... "*+123"
what i want is ..... "1 * 2 + 3"
im sure the answer is simple but I've racked my head on this.....I am a beginner
ive tried separating the first two positions and putting them into separate variables and alternated that way:
THIS IS MY CODE
formula = '*+*123'
first_part = formula[0:3]
second_part = formula[3:len(formula_chosen)]
print first_part
print second_part
expanded = ''
for i in range(len(second_part)-1):
expanded = expanded + second_part[i] + first_part[i]
print expanded
but what i end up with is: "1*2+"
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
you can simply write:
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.
Explained:
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("*+123")
is functionally equivalent to[(0, '*'), (1, '+'), (2, '1'), (3, '2'), (4, '3')]
. So we can use the positional argument ininput_a
and append to the corresponding character ininput_b
.input_a
will never be more than one character shorter than input_b.