removing numbers from string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    removing numbers from string

    Hi.....if I have a long string of numbers, letters, symbols, how can I remove the numbers but put them aside for use later on in the code? Example of string:

    e#pf3$@hzfvlkfs yx?1pdidasifkck yil@#6s0sod#9$u qwnb5u95f@0c9m0 99@tt?3

    -Thanks
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    If you have multiple strings to extract the digits, you can save them in a list. Otherwise, save the result by creating a single object reference. Example:
    Code:
    >>> s = 'e#pf3$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3'
    >>> sdigits = ''.join([letter for letter in s if letter.isdigit()])
    >>> sdigits
    '31609595090993'
    >>>

    Comment

    • Thekid
      New Member
      • Feb 2007
      • 145

      #3
      That works just fine :) Thank you I was trying some ''.join but couldn't get it right.

      Comment

      • Thekid
        New Member
        • Feb 2007
        • 145

        #4
        I have one more question on this.....after I 'print sdigits' and get the numbers, I try to 'print s' and the numbers are still there. How can I get it to where the numbers are removed from the string so I have 2 separate lists, one containing the numbers and one containing whats left? I've tried things like:

        s.replace
        s.split
        s.lstrip

        I can get it to take away one number with s.replace("1"," ") but that's it. If I try to make it:
        s.replace("('1' ,'2','3','4','5 ','6','7','8',' 9')", "")
        it doesn't work.

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Do it the same way, but add Python keyword not.
          Code:
          >>> s = 'e#pf3$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3'
          >>> sdigits = ''.join([letter for letter in s if letter.isdigit()])
          >>> severythingelse = ''.join([letter for letter in s if not letter.isdigit()])
          >>> severythingelse
          'e#pf$@hzfvlkfsyx?pdidasifkckyil@#ssod#$uqwnb uf@cm@tt?'
          >>>

          Comment

          • Thekid
            New Member
            • Feb 2007
            • 145

            #6
            Oh ok! Thanks again.

            Comment

            Working...