简体   繁体   English

如何从Python中的原始输入中提取某些数字?

[英]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. 让我们说他们给了我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? 我如何取字母jfh并将它们转换为一个单独的变量然后取数字12544并将它们放在一个单独的变量中?

>>> 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. for循环很简单。 Personally, I would use filter(). 就个人而言,我会使用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. 函数numalpha返回一个带有两个字符串的2元组,第一个字符串包含原始字符串中的所有字母字符,第二个字符串包含数字。

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. 请注意,这是非常低效的,因为它遍历字符串两次并且没有考虑数字和字母具有连续ASCII代码的事实,尽管它确实具有易于修改以与其他编码一起使用的优点。

Note also that I only extracted lower-case letters. 另请注意,我只提取了小写字母。 Yeah, It's not the best code snippet I've ever written xD. 是的,这不是我写过的最好的代码片段xD。 Hope it helps anyway. 无论如何希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM