I open a text file and add to the variable all its values ​​that look like this

aaa: bbbbbb

cccc: www

ww: gg

How do I implement a check whether this document contains the exact value (aaa: bbbbbb)? I tried through .find () and through if .. in ..., but when I entered, for example, a: b returns! = -1, and should work only if the entire line contains exactly the value that was entered. Tell me how to do this?

def login(login, password): logins = open('logins.txt', 'r') logins = logins.read() logpass = login + ":" + password if logins.find(logpass) != -1: return 1 else: return 0 
  • Is the content of the sequence in the string, or the entire file checked? - Tihon
  • Added screen, in fact - in the whole file - r4d1f

3 answers 3

You can simply read the file, convert the resulting line to a list where each line of the file is a list item, and check if the required combination is in the list.

 def login(login, password): with open("logins.txt", "r") as file: logins = file.read().split() logpass = login + ":" + password return logpass in logins 
  • This works as an example in the question, but it will not find the full line in the general case, when there may be a space inside the line. - jfs
  • @jfs Then you can use split('\n') . - user194374
  • @kff - yes, better so - I suggest you correct your answer, especially since the person accepted it - Sasha Che

To check whether the input file contains the specified string entirely:

 line = "aaa:bbbb" with open(filename) as file: if line in map(str.strip, file): print("{line} is in {filename}".format(**vars())) 

The code ignores spaces at the beginning / end of each line.

The code works because file is an iterator over strings (separated by "\ n") in Python.

     def is_logpass(*login_password: (str, str), file='logins.txt') -> bool: logpass = ':'.join(login_password) with open(file) as f: return any(logpass in line for line in f) is_logpass('aaa', 'bbbbbb') 
    • This code has the same problem as the code in question: it can find part of the string: a:b , instead of the entire string. - jfs