簡體   English   中英

如何使 txt 文件的搜索輸入不區分大小寫

[英]How to make search input case insensitive for txt file

現在代碼正在運行,但如果我不將名字和姓氏的第一個字母大寫,代碼將返回“錯誤:找不到人”。

如何設置它以便無論用戶如何輸入搜索,它都會返回請求的數據?

#Iterate through the lines and save them in a dictionary, with the
#full name as the key
for line in file:
    stripped = line.strip()
    name = stripped[:stripped.index(',')]
    d[name] = stripped[stripped.index(',')+1:].strip()

定義主():

#call the input function to read the file
addresses = input_address()

#Get the user option
option = int(input("Lookup (1) phone numbers or (2) addresses: "))

if option == 1:
    phone = True
else:
    phone = False

#Ask for names and print their information in case they exist, end on blank entry
while True:
    name = input("Enter space-separated first and last name: ")

    if name == "":
        return main()
    if name not in addresses:
        print("Error: person not found")
    else:
        display(addresses[name], phone)

主要的()

嘗試使用:

.capitalize()

例如:

'hello world'.capitalize()

產量,

'Hello World'

所以在你的情況下,你會這樣做:

name.capitalize()

然后在地址中查找它。

您可以使用lower()upper()capitalize() ,只要您將所選方法附加到兩個變量的末尾即可。

使用lower()

for i in range(len(addresses)):
   addresses[i] = addresses[i].lower()   # Converting array values to lowercase

if name.lower() not in addresses:    # Seeing if lowercase variable is in lowercase array
   print("Error: person not found")
else:
   print("Person found")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM