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

removing numbers from string

Thekid
100+
P: 145
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$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3

-Thanks
Feb 4 '09 #1
Share this Question
Share on Google+
5 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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:
Expand|Select|Wrap|Line Numbers
  1. >>> s = 'e#pf3$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3'
  2. >>> sdigits = ''.join([letter for letter in s if letter.isdigit()])
  3. >>> sdigits
  4. '31609595090993'
  5. >>> 
Feb 4 '09 #2

Thekid
100+
P: 145
That works just fine :) Thank you I was trying some ''.join but couldn't get it right.
Feb 4 '09 #3

Thekid
100+
P: 145
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.
Feb 4 '09 #4

bvdet
Expert Mod 2.5K+
P: 2,851
Do it the same way, but add Python keyword not.
Expand|Select|Wrap|Line Numbers
  1. >>> s = 'e#pf3$@hzfvlkfsyx?1pdidasifkckyil@#6s0sod#9$uqwnb5 u95f@0c9m099@tt?3'
  2. >>> sdigits = ''.join([letter for letter in s if letter.isdigit()])
  3. >>> severythingelse = ''.join([letter for letter in s if not letter.isdigit()])
  4. >>> severythingelse
  5. 'e#pf$@hzfvlkfsyx?pdidasifkckyil@#ssod#$uqwnb uf@cm@tt?'
  6. >>> 
Feb 4 '09 #5

Thekid
100+
P: 145
Oh ok! Thanks again.
Feb 5 '09 #6

Post your reply

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