The right way to do this is to simply slice the string, as in other answers.
But if you want a more concise way to write your own code that will work for similar problems that are not as simple as slicing, there are two tricks: comprehensions and enumerate .
First this loop:
for i in range(len(foo)): value = foo[i] something with value and i
... can be written as:
for i, value in enumerate(foo): something with value and i
So in your case:
for i, c in enumerate(s): if (i%2)==0: b+=c
Further, any cycle that starts with an empty object passes through an iterable (line, list, iterator, etc.) and places the values in a new iterable, it possibly runs values through an if filter or an expression that converts them can be easily turned into understanding.
While Python has options for lists, sets, dicts, and iterators, it has no concepts for strings, but str.join solves this.
So, connecting:
b = "".join(c for i, c in enumerate(s) if i%2 == 0)
Not as succinct or readable as b = s[::2] ... but much better than you started with the idea that the idea works when you want to do more complex things, for example if i%2 and i%3 ( which does not match any obvious fragment) or doubling each letter with c*2 (which can be done by stitching two slices, but this is not immediately obvious), etc.
source share