Skip to main content
 首页 » 编程设计

python之如何从用户输入中收集信息并将其应用到其他地方

2025年05月04日24fff_TT

你好,我是编程新手,我正在尝试编写一个代码,从输入中收集信息并确定它是否是一个有效的字母表。

到目前为止,这是我的代码

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.') 
 
suppose I choose three letters then the output of my code then pressed enter on the fourth,  
the code will be: 
 
Character:a 
Character:b 
Character:c 
Character: 
abc is a valid alphabetical string. 
 
I want to add to this code so that when I type in a character that is not 
from the alphabet the code will do something like this. 
 
Character:a 
Character:b 
Character:c 
Character:4 
4 is not in the alphabet. 

这就是我希望我的程序运行的方式

请您参考如下方法:

使用str.isalpha() 仅当字符串中的所有字符都是字母时才为真。

例子:

>>> 'test'.isalpha() 
True 
>>> 'test44'.isalpha() 
False 
>>> 'test test'.isalpha() 
False 

在您的代码中:

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