Skip to content Skip to sidebar Skip to footer

How To Check If Your File Is Left-justified

I'm writing a function that returns true if every line in the file is left justified that is first character is something other that space. Here is my code can someone tell me wher

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.

def justified(my_file):
    return not any(line[0] == ' ' for line in my_file)

Update: As pointed in comments, we could write it such that:

def justified(my_file):
    return not any(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')
def justified(my_file):
    for line in my_file:
        if line[0:1].isspace():
            return False
    return True

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.

with open("ex4.py", 'r') as file:
    for line in file:
        if line[0:1].isspace():
          return False
    return True

Solution 3:

You might like to consider whitespace characters other than just space in your check:

import string

whitespace = set(string.whitespace)

def justified(f):
    for line in f:
        if line[0] in whitespace:
            return False
    return True

which returns as soon as it finds a line that begins with whitespace.

This can be simplified to this code:

def justified(f):
    return not any(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"