Mar-08-2020, 09:00 PM
string.index raises a ValueError exception when the substring is not found. You can look for another function that returns a status instead of throwing an exception, but you should start getting used to using exceptions because they are used a lot in Python.
Your program will work better if you don't assume every string has to follow a particular pattern. I would write your function to try to process the string, determine if it is valid, if valid return the result, and if invalid print a message. Look a the invalid strings to help you determine if your parser is wrong or if the file contains strings with a different pattern that you can ignore or process differently
Python has really good tools for parsing strings. I think you might find regex interesting
def on_off_finder(in_string): #takes a string, looks for On or Off, return true if On try: start = in_string.index(" ") + 1 end = in_string.index("ch=") - 1 if in_string[start:end] == "On": return True elif in_string[start:end] == "Off": return False except ValueError: pass # Optionally do something else here return FalseI'm not exactly sure what this function is supposed to do other that what the comment describe. As it was written it looks like ever in_string is expected to contain "On" or "Off" and that this key will follow the first space and is immediately followed by "ch=". That is really restrictive syntax. Your code will throw a ValueError exception if the string doesn't include a space, or if it doesn't include "ch=" (exactly, including case).
Your program will work better if you don't assume every string has to follow a particular pattern. I would write your function to try to process the string, determine if it is valid, if valid return the result, and if invalid print a message. Look a the invalid strings to help you determine if your parser is wrong or if the file contains strings with a different pattern that you can ignore or process differently
Python has really good tools for parsing strings. I think you might find regex interesting