I have a file called strings.txt. I need to use isalmun() to see if the line has special characters or not.
my code so far:
file = open('strings.txt', 'r')
while True:
next_line = file.readline()
if not next_line:
break;
print(next_line.strip(),next_line.isalnum())
file.close()
But it doesn't give right results because each line has a linebreak \n which makes a proper line fail, output:
5345m345ƶ34l False
no2no123non4 False
noq234n5ioqw#% False
%#""SGMSGSER False
The second line should be True.
Code below shows that each line has \n
# -*- coding: UTF8 -*-
readfile = open("strings.txt","r")
content = readfile.readlines()
print(content)
for i in content:
print(i)
readfile.close()
Output:
['5345m345ƶ34l\n', 'no2no123non4\n', 'noq234n5ioqw#%\n', '%#""SGMSGSER\n', 'doghdp5234\n', 'sg,dermoepm\n', '43453-frgsd\n', 'hsth()))\n', 'bmepm35wae\n', 'vmopaem2234 0 \n', 'gsdm12313\n', 'bbrbwb55be3"?"#?\n', '"?"#%#"!%#"&"?%%"?#?#"?"\n', 'retrte#%#?%\n', 'abcdefghijklmnopqrstuvxy']
5345m345ƶ34l
How do I ignore the linebreak \n? I can't just join the lines or replace the linebreak because I need them to be as they are now, not as 1 single long line. Also I'm trying to figure out how to rename False and True to something else. I was able to rename them but only by printing the results in a new line instead of behind the existing lines.
CodePudding user response:
You can slice the string you are reading by 1 if they all end with a \n
next_line[:-1] then you can evaluate if it's alnum()
