I have a txt file, and I need to count the number of characters per line, then print the minimum, maximum value and range. Can anyone help me to build the code? Example (txt file):
lzaNDDRipfohkALungYAipuOhbWIpkmsSqvXkjRYNxCADTUKzS
aQLi
DwhhJfvUd
The output should be: Min: 4 character Max: 50 character Range: 46 character and NULL if the txt is empty
Can someone help me to build the code? ps. the TXT name must be inputted
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.