首页 > 解决方案 > Python 3.8(Luhn's Algorithm Alternative):如何将列表转换为字符串?

问题描述

我的问题是:如何将列表转换为字符串,尤其是在涉及打印命令时?

我正在尝试 Luhn's Algorithm 程序的变体,在该程序中我评估学生 ID 是否有效。在互联网的帮助下,我主要是去工作。但是,我还有最后一个障碍,使用 f 字符串,我应该通过打印出用户给我的 ID 号来结束。

问题是我将他们的输入从字符串转换为列表以运行算法,但我目前无法反转该过程。

这是我的相关代码:

ide = input("Hello.\nWelcome to the University of Zac Sign-In Page.\nPlease enter your Identification Number:")

if len(ide) != 6 and len(ide) != 10:
    print(f"I'm sorry, but {ide} is an invalid Identification Number.")
    print("Please try again... If the Headmaster Zac ever figures out how to program such an action.")
    
else:
    print("Yey.\n\nProcessing:")
    print(ide)
    
    ide = list(ide)
    print(ide)
    
    end_ide_nums = []
    
    for place, num in enumerate(ide):
        
        if place % 2 == 0:
            #print("Even!")
            double_ide_nums = int(num)*2
            if double_ide_nums > 9:
                double_ide_nums = double_ide_nums - 9
                # doubel_ide_nums = str(double_ide_nums)
                # double_ide_nums_1 = double_ide_nums[0]
                # double_ide_nums_2 = double_ide_nums[1]
                # end_ide_nums.append(int(double_ide_nums_1))
                # end_ide_nums.append(int(double_ide_nums_2))
                #C: The above was an attempt to make my code more different than my reference's (teclado's) code, but I could not get
                #       it to work. I kept getting syntax errors, particularly with the use of 'else:', and the explanations
                #       were not clear enough to me for me to fix the issue.
            end_ide_nums.append(double_ide_nums)
            
        else:
                end_ide_nums.append(int(num))
    
                         
    total = sum(end_ide_nums)
    
    print(total)
    
    if total % 10 == 0:
        ide = str(ide)
        print(f"{ide}--------VALID!")
    else:
        ide = str(ide)
        print(f"{ide}--------INVALID!")

例如,如果我的输入是 5555555555,这就是我想要摆脱的:

5555555555--------VALID!

但是,这是我的实际结果:

['5', '5', '5', '5', '5', '5', '5', '5', '5', '5']--------VALID!

请注意,我确实查看了其他类似的问题和给出的答案,但是这些问题已经足够不同了(而且我的无知足够强大)以至于我没有得到他们的帮助。我为愚蠢道歉,但我至少尝试过尽职调查。

任何和所有的帮助表示赞赏。以下是一些额外的资源:

这是我的代码的屏幕截图及其使用 Spyder 4 和 python 3.8 的输出。

请注意,我取得的大部分进展都非常感谢 tecado。

标签: python-3.xstringlistluhn

解决方案


推荐阅读