嗨,我想知道是否有一个Python中的数据类型只允许输入字母而不是数字

时间:2016-04-17 12:31:40

标签: python string list

我的代码是查找单词出现在列表中的位置,我需要它不接受数字作为输入。

sentence = input("What is your sentence? ")
List1 = sentence.split(' ')
List1 = [item.lower() for item in List1]
word = input("What word do you want to find? ")
word = word.lower()
length = len(List1)

counter = 0

while counter < length:
    if word == List1[counter]:
        print("Word Found In Position ",counter)
        counter += 1
    elif word != List1[counter]:
        counter += 1
    else:
        print("That word is not in the sentence")

这是我目前的代码。但是,它仍然接受数字。 我知道这是一个类似的问题:Asking the user for input until they give a valid response 但是我需要它以适应我现有的代码,我不知道如何。

1 个答案:

答案 0 :(得分:0)

从列表中筛选数字:

List1 = [s for s in List1 if not s.isdigit()]

如果长度为:

,则引发错误
[s for s in List1 if s.isdigit()]

大于0.

修改

添加了更好的号码检查。

def isdigit(s):
    """Better isdigit that handles strings like "-32"."""
    try:
        int(s)
    except ValueError:
        return False
    else:
        return True

添加到您的代码

while True:
    sentence = input("What is your sentence? ")
    List1 = sentence.split(' ')
    List1 = [item.lower() for item in List1]

    # Here is the check. It creates a new list with only the strings
    # that are numbers by using list comprehensions.
    #
    # So if the length of the list is greater then 0 it means there
    # are numbers in the list.
    if len([s for s in List1 if isdigit(s)]) > 0:
        print('You sentence contains numbers... retry!')
        continue

    word = input("What word do you want to find? ")
    word = word.lower()
    length = len(List1)

    counter = 0

    while counter < length:
        if word == List1[counter]:
            print("Word Found In Position ",counter)
            counter += 1
        elif word != List1[counter]:
            counter += 1
        else:
            print("That word is not in the sentence")