2016-08-25 158 views
-3

嗨,我是編程新手,我試圖編寫一個代碼,將收集來自輸入信息,並確定它是否是一個有效的字母表。如果字符是字母輸入驗證從輸入

我以前問過這個問題,但給出的答案只是沒有工作,所以我再次問這個問題。請幫助

words = [] 
word = input('Character: ') 
while word: 
if word not in words: 
    words.append(word) 
word = input('Character: ') 
print(''.join(words),'is a a valid alphabetical string.') 

想我選擇三個字母,然後我的代碼的輸出,然後按在第四輸入 , 代碼將是:

Character:a 
Character:b 
Character:c 
Character: 
abc is a valid alphabetical string. 

我想要添加到這個代碼,以便當我輸入字母表中不是 的字符時,代碼將執行類似的操作。

Character:a 
Character:b 
Character:c 
Character:4 
4 is not in the alphabet. 

這正是我希望我的輸出是。

enter image description here

+0

我已經表明了我所 – cars

+0

增加了一個回答你剛纔的問題。這個應該被標記爲重複。 – Karin

回答

0

如果你看一下串類,我認爲你會發現它有一些變量,你會發現有用的。

from string import letters 
word = raw_input("Character: ") 
words = [] 
while word and word in letters: 
    if word not in words: 
    words.append(word) 
    word = raw_input('Character: ') 

我沒有在這臺電腦上的Python,但我認爲你會發現這塊代碼的作品。此外,字符串類還有其他幾個變量,包括數字,標點符號,可打印等。

+0

我在哪裏可以將此代碼放在我的代碼 – cars

+1

好友中,這與您的代碼完全匹配。你應該能夠找出把這個放在哪裏。我想我沒有列印聲明。就這樣。 – bravosierra99

+0

你的問題是如何驗證字符是字母,而不是如何爲你寫整個問題。我已經給你回答你的問題。你應該能夠從這裏弄清楚。 – bravosierra99

0

您可以使用string.isalpha()函數來查找輸入是否爲字母。

>>> 'a'.isalpha() 
True  <-- as 'a' is alphabet 
>>> 'A'.isalpha() 
True  <-- as 'A' is also alphabet 
>>> ''.isalpha() 
False  <-- empty string 
>>> '1'.isalpha() 
False  <-- number 
------------------------- 
>>> 'ab'.isalpha() 
True  <-- False, since 'ab' is alphabetic string 

# NOTE: If you want to restrict user to enter only one char at time, 
# you may add additional condition to check len(my_input) == 1 
>>> len('ab') == 1 and 'ab'.isalpha() 
False 

爲了得到用戶的輸入,你可以這樣做:

  • 使用raw_input

    x = raw_input() # Value of x will always be string

  • 使用input

    x = input() # Value depends on the type of value

    x = str(x) if x else None # Convert to str type. In case of enter with value set as None

+0

我試過isalpha,你必須輸入字符串 – cars

+0

'raw_input()'返回所有字符串 –

+0

我的程序說錯誤原始輸入沒有定義 – cars