Search code examples
pythoncountmaxmintxt

Finding minimum, maximum and range of character count in every line of a TXT file


I have a text file and I need to count the number of characters per line and then print the minimum, maximum value and range. Example (txt file):

lzaNDDRipfohkALungYAipuOhbWIpkmsSqvXkjRYNxCADTUKzS
aQLi
DwhhJfvUd

The output should be:

  • Min: 4 characters
  • Max: 50 characters
  • Range: 46 characters

and NULL if the file is empty.


Solution

  • You can use the built-in min() and max() methods, using the built-in len() method as the keys:

    with open("file.txt", "r") as f:
        lines = f.read().splitlines()
    
    mi = len(min(lines, key=len))
    ma = len(max(lines, key=len))
    ra = ma - mi
    
    print(f"Min: {mi} Max: {ma} Range: {ra}")
    

    Output:

    Min: 4 Max: 50 Range: 46