2017-10-19 86 views
0

對於第三個elif,我試圖讓它檢測'Numb'中是否有任何特殊字符,並且是否有重複的while循環。如何查找輸入中是否有任何特殊字符

我一直在使用re.match與進口重新嘗試,但它似乎並不奏效

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') 

任何幫助將不勝感激,我仍然很新的這

+0

你的輸入是什麼? – anupsabraham

+0

發生了什麼,你想要發生什麼? – mrCarnivore

+0

1.使用小寫變量名; 2.不要使用'condition == True' – Dabiuteef

回答

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 
-1
import string 
    Numb = input('Enter the number you want to find the factorial of: ') 
    if len(set(string.punctuation).intersection(Numb)) > 0: 
     print('Do not enter any special characters.') 

這應該工作,我做我的腳本相反的(我只是與數據庫和密碼驗證發揮各地,但也有參數的密碼,如特殊字符,帽子等#

+0

這不是重點,這只是鰭d如果有特殊字符!在這裏批評我的代碼是愚蠢的。這沒有完整的代碼,他沒有要求那隻愚蠢的鵝。他有檢查這個數字是否沒有任何特殊字符的代碼。你也回答了,那麼這只是爲了與我競爭?我是新來的,不知道人們做了什麼,我認爲我們只是在這裏幫助別人,這就是我打算做的。 –

相關問題