Yes, your function would improve by adding [2:] there, but it might also lose range(len(original)) . Whenever you write range(len(something)) , you should step back and think about what you are actually trying to do.
In this case, you are looking for characters in a string, and you can get them more directly with for x in string . Here's a slightly improved version that takes these ideas into account:
def expand(original): var = "" symbols = original[:2] for digit in original[2:]: var += (digit + symbols) return var
This stops you from getting a weird mixture of characters at the beginning of the output, but it's still not perfect:
>>> expand('+*1234') '1+*2+*3+*4+*'
We need to find a way
- character selection alternately and
- leave them at the end of the line.
We can use itertools.cycle to process the first of them and a string slice for the second:
from itertools import cycle def expand(original): var = "" symbols = cycle(original[:2]) for digit in original[2:]: var += (digit + next(symbols)) return var[:-1]
This works, but at some point, someone is going to connect and tell you that you should not use + or += to create lines, because it is inefficient. If instead we create a list and then use str.join() to turn this into a string, we can improve things a bit:
from itertools import cycle def expand(original): chars = [] symbols = cycle(original[:2]) for digit in original[2:]: chars.extend([digit, next(symbols)]) return "".join(chars[:-1])
However, we can do better. Instead of calling next(symbols) every time, we can use zip() to get the next character and the next digit a couple at a time:
from itertools import cycle def expand(original): chars = [] for symbol, digit in zip(cycle(original[:2]), original[2:]): chars.extend([digit, symbol]) return "".join(chars[:-1])
... and that is probably enough :-)
EDIT . Since you said in a comment on another answer that you are not allowed to import anything from the standard library (rather silly IMO restrictions, but there), you can use the Python cycle() implementation described in the link earlier in this answer:
def cycle(iterable): # cycle('ABCD') --> ABCDABCDABCD ... saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element
... but you should probably be prepared to convince your teacher that you understand him, which means you need to understand yield .