首页 > 解决方案 > 使用 if 语句在字符串中搜索子字符串在类似变量类型中的行为不同

问题描述

我发布了两条代码,它们根据用户的输入在文件中进行搜索,并在其他值中打印出匹配的输出。

code(1) 使用按名称搜索,code(2) 使用按 mac 搜索。在 code(1) 的情况下,它不会返回任何匹配项,而在 code(2) 中它会正确返回匹配项,尽管所有变量类型都是 (string)!

代码(1)

searchbyname = input("Enter Device Name: ").lower()
with open(r"C:\Users\afahmy\Desktop\final2.txt", "r") as output_file:
    for line in output_file:
        ip = line.split(',')[0]
        password = line.split(',')[1]
        mac = line.split(',')[2].rstrip()
        name = line.split(',')[3].rstrip()
        if searchbyname in name:
            print(format("IP: " + ip + "\n" + "Password: " + password + "\n" + "Mac Address: " + mac + "\n" + "Device Name: " + name))

代码(2)

searchbymac = input("Enter mac-address: ").lower().replace(':', '')
with open(r"C:\Users\afahmy\Desktop\final2.txt", "r") as output_file:
    for line in output_file:
        ip = line.split(',')[0]
        password = line.split(',')[1]
        mac = line.split(',')[2].rstrip()
        name = line.split(',')[3].rstrip()
        if searchbymac in mac:
            print(format("IP: " + ip + "\n" + "Password: " + password + "\n" + "Mac Address: " + mac + "\n" + "Device Name: " + name))

运行具有两个代码的脚本时的输出

Enter Device Name: Test Phone - VVX411 << nothing returned and skip to the second piece of code
Enter mac-address: 64167f185bf3
IP: 10.10.10.10.5
Password: Password!
Mac Address: 64167f185bf3
Device Name: Test phone - VVX411

Process finished with exit code 0

对代码中可能有什么问题有任何解释或说明吗?

标签: pythonstringif-statement

解决方案


推荐阅读