How to write a function to remove digits from a str

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v13tn1g
    New Member
    • Feb 2009
    • 31

    How to write a function to remove digits from a str

    Given a string consisting of letters and digits only, return a list whose elements are those substrings of the given string that consist of consecutive letters only. For example, alpha("1up2down 33sideways77") will return the list ["up", "down", "sideways"].

    All i know is that i would have to use s.split()..i think?

    any help would be appreciated. thanks.
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    I haven't seen any built in string functions that look like they could do this for you, although isalpha() could be useful. myString.isalph a() returns true if all the characters in myString are letters. You'll probably have to loop through each character in the string, put it in your list if it's a letter, and append a new string to your list if you find the beginning of a new word.
    I hope this gives you some idea of how to solve the problem.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      re.split() should work well for this task.
      Code:
      >>> import re
      >>> re.split('[0-9]', '1up2down33sideways77')
      ['', 'up', 'down', '', 'sideways', '', '']
      # eliminate null strings with a list comprehension
      >>> [item for item in re.split('[0-9]', '1up2down33sideways77') if item]
      ['up', 'down', 'sideways']
      >>>

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Wow, bvdet. Looks like I'd better read up on the re module.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          The re module is very powerful, but it can be cryptic and difficult. Here's a good tutorial: click here

          Here's another, not so succinct method of achieving the same result:
          Code:
          aStr = "1up2down33sideways77"
          
          # create a list of indices of the digits in aStr
          idxList = [i for i, s in enumerate(aStr) if s.isdigit()]
          print idxList
          strList = [aStr[idxList[i]+1:idxList[i+1]] for i in range(len(idxList)-1)]
          # this list will contain null strings
          print strList
          
          # similar to the list comprehension above, eliminates null strings
          strList2 = []
          for i in range(len(idxList)-1):
              s = aStr[idxList[i]+1:idxList[i+1]]
              if s:
                  strList2.append(s)
          
          print strList2

          Comment

          Working...