Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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'
>>> 
like image 321
eagertoLearn Avatar asked Dec 30 '13 20:12

eagertoLearn


People also ask

How do you use alternate case of string in Python?

Method #1 : Using upper() + lower() + loop This task can be performed in brute force method in a way that we iterate through the string and convert odd elements to uppercase and even to lower case using upper() and lower() respectively.

How do you remove alternate characters in a string in Python?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

>>> 'abcdefg'[::2]
'aceg'
like image 119
Maciej Gol Avatar answered Oct 03 '22 02:10

Maciej Gol


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

like image 21
Stryker Avatar answered Oct 03 '22 04:10

Stryker