如何让python检查字符串的特定长度?

2024-09-28 01:32:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做作业,我有点不知所措。我的任务之一是,我需要一个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.")

Tags: thenumberinputlenifisnotcard
3条回答

Python没有开关函数,所以可以使用if elif或{}。在

你的案子绝对是字典式的。在

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")

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

如果卡片长度是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]。在

你可以试试这样的方法:

#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的第一个字符?在

相关问题 更多 >

    热门问题