如何从输入中仅排除数字、标点符号?python

如何从输入中仅排除数字、标点符号?python,python,Python,有没有办法制定一个规则,输入的答案可能只有字符串或字符串+数值,没有标点符号/空格。所以看起来是这样的 Insert first name: … … name: 5363737 - **not allowed** … name: Bird1 ! - **not allowed** … name: Bird1 - **allowed** 无论您“插入”什么,都可能有自己的验证函数,但如果没有,它将是一个用于过滤的简单正则表达式 import re inserts = [ 'aBC12

有没有办法制定一个规则,输入的答案可能只有字符串或字符串+数值,没有标点符号/空格。所以看起来是这样的

Insert first name:  …
… name: 5363737 - **not allowed**
… name: Bird1 ! - **not allowed**
… name: Bird1 - **allowed**
无论您“插入”什么,都可能有自己的验证函数,但如果没有,它将是一个用于过滤的简单正则表达式

import re

inserts = [
    'aBC123',
    'ABC 123',
    'i like pie.',
    '123abc',
]

for i in inserts:
    if re.match('^[a-zA-Z]+[0-9]*$', i):
#   if re.match('^[a-zA-Z0-9]*$', i):   #leaving my old error visible as a testament to the importance of reading the spec carefully.
        print('insert', i)
        # call insert function
    else:
        print('NOT inserting', i)
        # do whatever

不带
re
模块:

from string import letters, digits
from itertools import chain

while True:
    user_input = input('Insert first name: ')
    if all(c in digits for c in user_input) or #invalid if only numbers   
       any(c not in chain(letters,digits) for c in user_input): #invalid if something else than letters+numbers
        print 'name: ' + user_input + '** not allowed **'
    else:
        print 'name: ' + user_input + '** allowed **'
        break

在大约5分钟后,当你决定正则表达式是你的新上帝时,你会想知道这个网站@Moontego:你确定这段代码符合你的要求吗?它将匹配类似于
5363737
不,我使用了@LetzerWille的代码。这个不行。是的,我道歉。在我跑出门误读你想要的东西之前,我想给你买点东西@LetzerWillie说得对。python的
代码在哪里?你是想验证用户键入的内容,还是想禁止用户键入特定字符?嘿,我使用了你的代码,它几乎可以正常工作。唯一的问题是它不允许例如“Bird1923812”。规则必须是这样,我可以使用任何字符+数值,但现在它受到0-9的限制。如何更改正则表达式,使其接受字符后面的所有数字?我尝试了重新匹配(r'([A-Za-z][\d])+$,但没有成功。我非常感谢。它现在确实有效。我刚进入大学的第一学期,有些作业有点太难:)再次感谢!我遇到了一个新问题。现在它不接受常规的“唯一字符”输入。例如,“鸟”也是允许的。它不必是“Bird1,bird1239”。所以它也需要接受常规字符输入。@Moontego好的,看一看。是的,现在看起来它完成了。:)再次感谢!
from string import letters, digits
from itertools import chain

while True:
    user_input = input('Insert first name: ')
    if all(c in digits for c in user_input) or #invalid if only numbers   
       any(c not in chain(letters,digits) for c in user_input): #invalid if something else than letters+numbers
        print 'name: ' + user_input + '** not allowed **'
    else:
        print 'name: ' + user_input + '** allowed **'
        break