Program to extract each alternate letter from string in python?

Python programs are often short and concise, and usually require a set of lines in other programming languages ​​(which, as I know), can execute in a line or two in python. One such program I'm trying to write is to extract all the other letters from a string. I have this working code, but I wonder if any other concise way is possible?

>>> s 'abcdefg' >>> b = "" >>> for i in range(len(s)): ... if (i%2)==0: ... b+=s[i] ... >>> b 'aceg' >>> 
+6
source share
5 answers
 >>> 'abcdefg'[::2] 'aceg' 
+18
source

Use Explain Python snippet notation :

 >>> 'abcdefg'[::2] 'aceg' >>> 

Slice notation format [start:stop:step] . So [::2] tells Python to go through the string by 2 (which will return any other character).

+12
source

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.

+3
source

you can try using a slice and join:

 >>> k = list(s) >>> "".join(k[::2]) 'aceg' 
0
source

In practice, slicing is the best way to go. However, there are also ways to improve existing code, not shorten it, but make it more Pythonic:

 >>> s 'abcdefg' >>> b = [] >>> for index, value in enumerate(s): if index % 2 == 0: b.append(value) >>> b = "".join(b) 

or even better:

 >>> b = "".join(value for index, value in enumerate(s) if index % 2 == 0) 

This can easily be extended to more complex conditions:

 >>> b = "".join(value for index, value in enumerate(s) if index % 2 == index % 3 == 0) 
0
source

All Articles