如何查找输入中是否有任何特殊字符

时间:2017-10-19 14:01:02

标签: python python-3.x import detection

对于第三个elif,我试图让它成为检测“Numb”中是否有任何特殊字符以及是否重复while循环。

我尝试使用re.match和import re但它似乎没有工作

Numb = input('Enter the number you want to find the factorial of: ')

if Numb.isalpha() == True:      
    print ('You can\'t find the factorial of a letter stupid! Try a digit 
next time')
elif int(Numb) <0:
    print ('You cannot find the factorial of a negative number')
elif Numb >=0 and Numb.isdigit() == True:
    print ('::::::::::::::::' ':'*len(Numb))
    print ('you have chosen', Numb)
    print ('::::::::::::::::' ':'*len(Numb))
    Con +=1
elif re.match("^[a-zA-Z0-9]*$", Numb):
    print ('Do not enter any special characters. e.g. \' \' or \'.\'')

else:
    print ('Please entar an integer that is 0 or above')

任何帮助都会非常感激,我仍然很擅长这个

1 个答案:

答案 0 :(得分:1)

您需要使用 re.search()而不是 re.match() ! 您的正则表达式应检查一个或多个( + )而不是一个特殊字符

re.search("[^a-zA-Z0-9]+", Numb)

检查一个或多个是否会检查与或更多特殊字符的匹配,这不是您问题中的预期特征!

示例IO:

>>> re.search("[^a-zA-Z0-9]+","2343") #false
>>> re.search("[^a-zA-Z0-9]+","2343$") #true
<_sre.SRE_Match object at 0x7fdcbaed07e8>
>>> re.search("[^a-zA-Z0-9]+","2343$3534") #true
<_sre.SRE_Match object at 0x7fdcbaed08b8>
>>> re.search("[^a-zA-Z0-9]+","2345$$$43") #true
<_sre.SRE_Match object at 0x7fdcbaed07e8>
>>> re.search("[^a-zA-Z0-9]+","34dsf") #false
>>> re.search("[^a-zA-Z0-9]+","fdsf") #false