开发者

How do I extract certain digits from raw input in Python?

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 开发者_如何学Cthem in a separate variable?


>>> 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']


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜