[英]How to exclude only numbers, punctuation marks from input? Python
Is there any way to make a rule, where answer to the input may be only String or string+numeric value without punctuation marks/space. 有没有办法制定规则,其中输入的答案可能只是字符串或字符串+数值,而没有标点符号/空格。 So that will look like.
这样看起来像。
Insert first name: …
… name: 5363737 - **not allowed**
… name: Bird1 ! - **not allowed**
… name: Bird1 - **allowed**
Whatever you are "inserting" with might have its own validation functions, but if not, its a straightforward regular expression to filter with. 无论您“插入”什么,都可能具有其自己的验证功能,但如果没有,则可以使用其直接过滤的正则表达式。
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
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))
Without re
module: 不带
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.