Let's say I ask a users for some random letters and numbers. let's say they gave me 1254jf4h. How would I take the letters jfh and convert them inter a separate variable and then take the numbers 12544 and make them in a separate variable?
+2
A:
>>> s="1254jf4h"
>>> num=[]
>>> alpah=[]
>>> for n,i in enumerate(s):
... if i.isdigit():
... num.append(i)
... else:
... alpah.append(i)
...
>>> alpah
['j', 'f', 'h']
>>> num
['1', '2', '5', '4', '4']
ghostdog74
2010-10-09 16:23:35
Thanks man! This works like I wanted it to!!!
Noah Brainey
2010-10-09 16:26:38
Why are you enumerating s? Make that `for i in s:` since you never use n.
Just Some Guy
2010-10-09 17:02:01
@Just Some Guy. does it matter? You assume OP doesn't need it, I assume OP will need it. Is that all right with you?
ghostdog74
2010-10-10 01:55:23
It kind of does matter in that it's slower (because you're wrapping a simple iterable in the enumerator generator) and pollutes the namespace with an unused variable, but doesn't add anything whatsoever to the outcome. It's wholly unneeded. You could sprinkle the code with `pass` and `if True:` and it would still yield the same output, but it wouldn't make the code work better. Neither does the `enumerate` in this case.
Just Some Guy
2010-10-10 04:27:34
Slower? who cares? Like i said, it depends on OP. If he don't need it, he can remove it. I just feel like using enumerate, since i don't know what's OP's setup. Don't tell me you knew what OP really wants? So what do you want to do about it? still continue this trivial debate?
ghostdog74
2010-10-10 05:14:11
I'm bowing out. You seem to be much more invested in this than I care to be. Have a great week!
Just Some Guy
2010-10-10 05:30:17
its only because you cared in the first place, that i bothered to reply. have a great week too
ghostdog74
2010-10-10 05:49:43
A:
edit: oh well, you already got your answer. Ignore.
NUMBERS = "0123456789"
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def numalpha(string):
return string.translate(None, NUMBERS), string.translate(None, LETTERS)
print numalpha("14asdf129h53")
The function numalpha returns a 2-tuple with two strings, the first containing all the alphabetic characters in the original string, the second containing the numbers.
Note this is highly inefficient, as it traverses the string twice and it doesn't take into account the fact that numbers and letters have consecutive ASCII codes, though it does have the advantage of being easily modifiable to work with other codifications.
Note also that I only extracted lower-case letters. Yeah, It's not the best code snippet I've ever written xD. Hope it helps anyway.
Santiago Lezica
2010-10-09 16:32:36
+1
A:
A for loop is simple enough. Personally, I would use filter().
s = "1254jf4h"
nums = filter(lambda x: x.isdigit(), s)
chars = filter(lambda x: x.isalpha(), s)
print nums # 12544
print chars # jfh
Nick Presta
2010-10-09 17:02:59