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

2024-09-21 00:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Insert first name:  …
… name: 5363737 - **not allowed**
… name: Bird1 ! - **not allowed**
… name: Bird1 - **allowed**

Tags: 字符串答案name规则not数字firstinsert
3条回答

无论你用什么“插入”都可能有它自己的验证函数,但是如果没有,那就是一个简单的正则表达式来过滤。在

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
    Code:

     or i in "5363737","Bird1 !", "Bird1", "Bird1923812", "Bird":

        mo = re.match(r'([A-Za-z]+[0-9]*)$',i)

        if mo:
            print("allowed {}".format(mo.group(0)))
        else:
            print("not allowed {}".format(i))

    not allowed 5363737
    not allowed Bird1 !
    allowed Bird1
    allowed Bird1923812
    allowed Bird

# if needed, as stated in the comment  char+number+char, number+char, 
# number+char+number.
for i in "536cat3737","Bird1 !", "Bird1", "Bird1923812bird", "Bird","777Bird":

    mo = re.match(r'([A-Za-z]*[0-9]+[A-Za-z]+|\d+[A-Za-z]+\d+)$',i)

    if mo:
        print("allowed {}".format(mo.group(0)))
    else:
        print("not allowed {}".format(i))

相关问题 更多 >

    热门问题