program to extract every alternate letters from a string in python?

Viewed 63312

Python programs are often short and concise and what usually requires bunch of lines in other programming languages (that I know of) can be accomplished in a line or two in python. One such program I am trying to write was to extract every other letters from a string. I have this working code, but wondering 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 Answers

Here is another example both for list and string:

sentence = "The quick brown fox jumped over the lazy dog."

sentence[::2]

Here we are saying: Take the entire string from the beginning to the end and return every 2nd character.

Would return the following:

'Teqikbonfxjme vrtelz o.'

You can do the same for a list:

colors = ["red", "organge", "yellow","green", "blue"]
colors[1:4]

would retrun:

['organge', 'yellow', 'green']

The way I read the slice is: If we have sentence[1:4] Start at index 1 (remember the starting position is index 0) and Stop BEFORE the index 4

Related