Firstly, you can simplify your code with enumerate
:
for x, line in enumerate(f, 1):
Secondly, you can use startswith
and endswith
to test strings:
if (x == num / 2 and
len(sms_word) <= len(line) < 2 * len(sms_word) and
line.startswith(sms_word[0]) and
line.endswith(sms_word[-1])):
Finally, lines from the file will have a newline character '\n'
at the end, so strip()
them first:
line = line.strip()