(Python) How to handle and work with each distinct lines in a string?

Question:

I am trying to do exercise about "Filtering the file contents" and here is the full questions:

Create a program which reads all of the lines from the file and tests the lines. If the line has only letters and/or numbers, the program prints "[line] was ok.". If the line has special characters, the program should print "[line] was invalid.". When the program works, it prints out something like this:

>>> 
5345m345ö34l was ok.
no2no123non4 was ok.
noq234n5ioqw#% was invalid.
%#""SGMSGSER was invalid.
doghdp5234 was ok.
sg,dermoepm was invalid.
43453-frgsd was invalid.
hsth())) was invalid.
bmepm35wae was ok.
vmopaem2234+0+ was invalid.
gsdm12313 was ok.
bbrbwb55be3"?"#? was invalid.
"?"#%#"!%#"&"?%%"?#?#"?" was invalid.
retrte#%#?% was invalid.
abcdefghijklmnopqrstuvxy was ok.
>>>       

It is advisable to read the lines one at a time, test them with the isalmun() string test and go on from there. Also remember that the strings may also end in a line break (n), which is allowed, but fails the .isalnum() test if not sliced away.

Here is my implementation:

n=open("strings.txt","r")
x=n.read()
if x.isalnum()==True:
    print(x,"  was ok")
else:
    print(x," was invalid")
n.close()

And the system’s response:

5345m34534l
no2no123non4
noq234n5ioqw#%
%#""SGMSGSER
doghdp5234
sg,dermoepm
43453-frgsd
hsth()))
bmepm35wae
vmopaem2234+0+
gsdm12313
gswrgsrdgrsgsig45
)/(/)(#=%#)%/
++-+-+--+--+-+>-<+-<<_<-+>>++.
  was invalid

I really don’t know how to solve this. Please help me with what I have missed

Thank you in advance!!!

Asked By: Danh Nguyễn

||

Answers:

something like this – the code needs to loop over the file line by line

with open('strings.txt') as f:
  lines = [l.strip() for l in f.readlines()]
  for line in lines:
    if line.isalnum():
      print(f'{line} was ok')
    else:
      print(f'{line} was invalid')
Answered By: balderman

You may need to loop over your lines with a for loop. The way you’re doing it now is, that all of your lines are stored under x.
Something like this:

file = open("strings.txt","r")

for line in file:
  if line.isalnum()==True:
    print(line,"  was ok")
  else:
    print(line," was invalid")

file.close()
Answered By: Tilen Pintarič
     n = open("strings.txt", "r", encoding="utf8")
for line in n:
    if line.strip().isalnum():
        print(line.strip(), " was ok")
    else:
        print(line.strip(), " was invalid")
n.close()

x = n.read() is a string consisting of all lines of the file . you need to read the file line by line with for.

strip() – Remove spaces at the beginning and at the end of the string,

Answered By: RomanR
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.