Python 如何允许用户只输入字母?

Python 如何允许用户只输入字母?,python,Python,我正试图让编码选项发挥作用,这样,如果用户在字符串中输入一个数字,它将用“请仅限字母”回复并重新提示用户。现在我得到一个错误: Traceback (most recent call last): File "/Users/myname/Desktop/proj01.py", line 16, in <module> c = c + 1 TypeError: can only concatenate str (not "int") to str 您可以使用字符串的isa

我正试图让编码选项发挥作用,这样,如果用户在字符串中输入一个数字,它将用“请仅限字母”回复并重新提示用户。现在我得到一个错误:

Traceback (most recent call last):
  File "/Users/myname/Desktop/proj01.py", line 16, in <module>
    c = c + 1
TypeError: can only concatenate str (not "int") to str

您可以使用字符串的
isalpha
方法确认输入为字符串,如果字符串仅包含字母,则返回
True
,否则返回
False

prompt1 = input("Select a commend: \n'e' to encode,\n'd' to decode, or\n'q' to quit\n")
if not prompt1.isalpha():
    #prompt1 does not contain only letters, deal with it here.

在需要确认字符串仅包含字母的任何位置使用
isalpha

可以直接在字符串上使用
isalpha()
,而不是在每个字母上使用。抛出此错误是因为
'1'
仍将被视为
str
而不是
int
for
循环之前,您已将
c
初始化为
0
,并且正在使用同名变量迭代
prompt2
c
将始终是
str
类型。您的
c
值包含字符串(type)。因此,您可以在Python控制台中执行一个小测试:
test=“text”+1
。。。当然,什么会引起错误。如果要在和之间转换ASCII字符(“字符”),请使用
ord()
str()
在这两种类型之间进行转换。例如:
ord(65)
给你
“一个”
字符串(一个字符)和
str(“A”)
给你整数
65
。如果您想反映Unicode字符,则需要稍微长一点的解释。
prompt1 = input("Select a commend: \n'e' to encode,\n'd' to decode, or\n'q' to quit\n")
if not prompt1.isalpha():
    #prompt1 does not contain only letters, deal with it here.