By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,790 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

removing a letter from a sentence

P: n/a
I am trying to remove every other letter from a sentence that I input just by using a for loop. This code however just reprints the sentence
Expand|Select|Wrap|Line Numbers
  1. def removeLetter(sentence):
  2.     index=0
  3.     for letter in sentence:
  4.         index=index+1
  5.         if index%2==0:
  6.             letter=""
  7.             sentence=sentence+letter
  8.             return sentence
Oct 1 '10 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
You assign letter to a null string and then add it to sentence, in effect doing nothing. The following code uses a list comprehension to create a list of the letters you want to keep, then joins the letters into a new abbreviated sentence.
Expand|Select|Wrap|Line Numbers
  1. >>> s = "This is a test sentence."
  2. >>> "".join([letter for i, letter in enumerate(s) if not i%2])
  3. 'Ti sats etne'
  4. >>> 
Oct 1 '10 #2

Expert 100+
P: 621
You have to add the desired letters to a new string, or convert the original string to a list. Note also that the return statement doesn't have the correct indent.
Expand|Select|Wrap|Line Numbers
  1. def removeLetter(sentence):
  2.     index=0
  3.     new_sentence = ""
  4.     for letter in sentence:
  5.         index=index+1
  6.         if index%2==0:
  7.             new_sentence += letter
  8.     return new_sentence 
Oct 1 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.