简体   繁体   中英

Python specific find in file

I'm trying to learn python with learning by doing way, but i have a problem with my code. Trying to do a code, where you input IP and code will check, if IP is in the ips.txt file, but when i add for example "192.168.0.10" and in file already is "192.168.0.100" then it will show, that "192.168.0.10" is in txt file, because "10" is part of the "100" number.

The same example is "dog" and "dogs", "dog" is basically inside "dogs", so it will tell that dog is in file...

Can you help me with it? Thanks

IPs = IPs.read()
IP = input("Check IP: ")
if IP in IPs:
    print("IP is in the list.")
else:
    print("IP is not in the list.") ```

IPs.read() produces a string. This means when you perform IP in IPs , it's checking whether the string IP is a substring of IPs (it performs a substring search ). In your situation, notice "" in IPs , "1" in IPs and ".1" in IPs will all evaluate to True .

What you want is IPs to be a list of strings, which can achieved via:

IPs = IPs.read().splitlines()

This reads the input and splits the string by newlines, so if the text files contains:

192.168.0.10
192.168.0.9
192.168.0.7

IPs will be:

["192.168.0.10", "192.168.0.9", "192.168.0.7"]

So now, when you do IP in IPs it will linear search for the value IP in IPs . Linear search takes O(n) time, where n is the length of the list. If the order of IPs doesn't matter and you're making a lot of lookups, I recommend turning the list into a set via IPs = set(IPs.read().splitlines()) . This way, when you do IP in IPs , the time to lookup is constant, no matter the size of the list (aka program go zoom).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM