1

The picture shows that everything else works properly instead there is an empty space in the code and that makes the program print "was invalid." I have no idea where the empty space comes from, any suggestions?

selec1 = open("strings.txt","r")
selec2 = "bob"
while selec2:
    selec2 = selec1.readline().replace("\n","")
    if selec2.isalnum() == True:
        print(selec2,"was ok.")
    if selec2.isalnum() == False:
        print(selec2,"was invalid.")
ti7
  • 16,375
  • 6
  • 40
  • 68
Jussi
  • 13
  • 2

1 Answers1

0

I would do this iterating by-lines, which may be what's intended

For example

with open("strings.txt") as fh:  # close file when leaving scope
    for line in fh:              # file-likes are iterable by-lines
        line = line.strip()      # remove trailing newline
        print("{} was {}.".format(line, "ok" if line.isalnum() else "invalid"))

This does a few helpful things

  • using with open() instead of open() will close the file when you're done with it
  • calling .strip() on the line (as noted in comments) will remove trailing newline chars from lines more easily than replacing them
  • open() returns a file-like, which is already iterable by-lines (so you can simply write a structure like for x in y) and will omit a trailing final line
  • you can make a structure like "a" if something else "b" to simplify some flows
ti7
  • 16,375
  • 6
  • 40
  • 68