strings

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wanstrjm
    New Member
    • Sep 2007
    • 1

    strings

    How do I get the digits out of a string?
    Example: string1 = "23.45a"
    I need to remove the alpha characters and keep the digits.
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by wanstrjm
    How do I get the digits out of a string?
    Example: string1 = "23.45a"
    I need to remove the alpha characters and keep the digits.
    Like this?
    [code=python]
    string1 = "23.45a"

    digits = [int(c) for c in string1 if c.isDigit()] # not sure about the isDigit method

    #import string
    #digits = [int(c) for c in string1 if c in string.digits]
    [/code]

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      This solution uses module re:[code=Python]import re
      string1 = "23.45a"
      string2 = "23.a"
      string3 = ".45a"
      patt = re.compile(r'(\ d*.\d*)')

      print float(patt.sear ch(string1).gro up(1))
      print float(patt.sear ch(string2).gro up(1))
      print float(patt.sear ch(string3).gro up(1))[/code]

      >>> 23.45
      23.0
      0.45
      >>>

      Comment

      • ghostdog74
        Recognized Expert Contributor
        • Apr 2006
        • 511

        #4
        make use of existing string functions
        Code:
        ''.join([i for i in list(s) if not i.isalpha()])

        Comment

        Working...