python - 使用 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
对代码中可能有什么问题有任何解释或说明吗?
解决方案
推荐阅读
- c - 如何在c中以优雅的方式将json转换为struct
- python - 如何用python从我的电脑打开一个程序?
- edi - EDI 832 输入表
- java - 在春季通过响应返回组的最佳方式
- uwp - BufferingStarted 和 PlaybackSession.BufferingStarted 有什么区别
- android - view.post() 和 GlobalScope.launch(Dispatchers.Main) 有什么区别?
- python - 从文本文件中提取数据以在 matplotlib 中绘制图形时突出显示一点
- python - 图片 - CNN 澄清
- google-apps-script - 如何将来自 2 个不同列的数据同步到另一个电子表格?
- javascript - 按名称/数量组织对象数组