如何对字符串的特定长度进行python检查?

时间:2018-03-20 16:19:15

标签: python string python-3.x

我正在做一些功课,我有点难过。我的任务的一部分是我需要一个If语句来检查输入的数字是否是16个字符长,这是我到目前为止的代码:

#the input
CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")

#The if statements
if str(CreditCardNum) != len(16):
    print("This is not a valid number, make sure the number is 16 characters.")
elif str(CreditCardNum) == len(16):
    if str(CreditCardNum[0:]) == 4:
        print("The Card is a Visa")
    elif str(CreditCardNum[0:]) == 5:
        print("The Card is a Master Card")
    elif str(CreditCardNum[0:]) == 6:
        print("The Card is a Discover Card.")
    else:
        print("The brand could not be determined.")

3 个答案:

答案 0 :(得分:1)

这是我相信你正在寻找的逻辑。

如果卡片长度为16,则会检查第一个字符以确定哪种类型。

CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")

n = len(CreditCardNum)

if n != 16:
    print("This is not a valid number, make sure the number is 16 characters.")
else:
    x = CreditCardNum[0]
    if x == '4':
        print("The Card is a Visa")
    elif x == '5':
        print("The Card is a Master Card")
    elif x == '6':
        print("The Card is a Discover Card.")
    else:
        print("The brand could not be determined.")

<强>解释

  • 使用n = len(CreditCardNum)在变量n中存储输入字符串中的字符数。同样是输入的第一个字符。
  • len(16)没有逻辑意义。您想将n(一个整数)与另一个整数进行比较。
  • 要提取字符串的第一个字母,只需执行mystr[0]

答案 1 :(得分:1)

Python没有切换功能,因此您可以使用if elifdictionary

您的案例肯定是字典类型。

card_dict = {
    '4': "Visa",
    '5': "Master card",
    '6': "Discover card"
}
CreditCardNum = input("Input a credit card number(no 
spaces /hyphens): ")

n = len(CreditCardNum)
x = CreditCardNum[0]
if n != 16:
    print("This is not a valid number, make sure the number is 16 characters.")
elif x in card_dict:
    print("The Card is a {}".format(card_dict[x]))
else:
    print("The brand could not be determined")

答案 2 :(得分:0)

您可以尝试这样的事情:

#the input
CreditCardNum = input("Input a credit card number(no spaces/hyphens): ")

#The if statements
if len(str(CreditCardNum)) != 16:
    print("This is not a valid number, make sure the number is 16 characters.")
elif len(str(CreditCardNum)) == 16:
    if str(CreditCardNum[0]) == '4':
        print("The Card is a Visa")
    elif str(CreditCardNum[0]) == '5':
        print("The Card is a Master Card")
    elif str(CreditCardNum[0]) == '6':
        print("The Card is a Discover Card.")
    else:
        print("The brand could not be determined.")

我不确定您在外部elif内的条件语句中尝试做什么,但我假设您正在尝试获取CreditCardNum的第一个字符?