removing a letter from a sentence

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mike Andrews

    removing a letter from a sentence

    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
    Code:
    def removeLetter(sentence):
        index=0
        for letter in sentence:
            index=index+1
            if index%2==0:
                letter=""
                sentence=sentence+letter
                return sentence
    Last edited by bvdet; Oct 1 '10, 12:57 PM. Reason: Add code tags [code]....code goes here....[/code]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    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.
    Code:
    >>> s = "This is a test sentence."
    >>> "".join([letter for i, letter in enumerate(s) if not i%2])
    'Ti sats etne'
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      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.
      Code:
      def removeLetter(sentence):
          index=0
          new_sentence = ""
          for letter in sentence:
              index=index+1
              if index%2==0:
                  new_sentence += letter
          return new_sentence

      Comment

      Working...