How To Check If Your File Is Left-justified
Solution 1:
line[0:2] == ' '
checks first two characters. According to your description, you'd like to check first character such that line[0] == ' '
.
Also, no need to read more after finding one. Otherwise, you can override it.
defjustified(my_file):
returnnotany(line[0] == ' 'for line in my_file)
Update: As pointed in comments, we could write it such that:
defjustified(my_file):
returnnotany(line.startswith(' ') for line in my_file)
Then, it reads very similar to natural language.
Solution 2:
You should short-circuit your conditional-if
; It appears that as long as the final line in your file is justified the result will be set to True. Additionally your check for whitespace doesn't exactly work, but you can use a function like .isspace() which will check for whitespace in your substring that you are passing. Finally, notice the substring you are obtaining is actually taking in 2 characters, not one.
my_file = open("ex4.py", 'r')
defjustified(my_file):
for line in my_file:
if line[0:1].isspace():
returnFalsereturnTrue
This has the benefit of not having to parse through the entire file as soon as we know that it is not left-justified.
Alternatively, you may find it convenient to use this setup when working with files as it will close the file for you.
withopen("ex4.py", 'r') as file:
for line in file:
if line[0:1].isspace():
returnFalsereturnTrue
Solution 3:
You might like to consider whitespace characters other than just space in your check:
import string
whitespace = set(string.whitespace)
defjustified(f):
for line in f:
if line[0] in whitespace:
returnFalsereturnTrue
which returns as soon as it finds a line that begins with whitespace.
This can be simplified to this code:
defjustified(f):
returnnotany(line[0] in whitespace for line in f)
This will treat empty lines, i.e. those beginning with new line (\n
), carriage return (\r
) (and consequently both \r\n
) as not being justified. If you wanted to ignore empty lines you could remove the relevant characters from the set:
whitespace = set(string.whitespace) - {'\n', '\r'}
Post a Comment for "How To Check If Your File Is Left-justified"