gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:16 26 4
gpt4 key购买 nike

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

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

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.

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

enter image description here

enter image description here

最佳答案

使用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.')

关于python - 如何从用户输入中收集信息并将其应用到其他地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com