Reputation: 13
I am trying to get the longest and shortest name from a file and print it out. If two people's names are the same length and are the biggest/smallest I also need to print that out.
What I tried:
try:
marvel_number = 0
with open("Marvel.txt") as numbers_file:
for line in numbers_file:
marvel_number = marvel_number + 1
print(len(marvel_number))
When I ran this code it gave me this error:
TypeError: object of type 'int' has no len()
This is the Marvel.txt file which I am trying to read from
Upvotes: 1
Views: 1124
Reputation: 7846
You could iterate over all these names in the file, store them in a list called names
and then sort that list based on each item's length. By default, Python's order is ascending, so the shortest name is the first element and the longest name is the last element:
with open('marvel.txt', 'r') as numbers_file:
names = sorted([line.strip() for line in numbers_file], key=len)
print('Shortest name: ' + names[0])
print('Longest name: ' + names[-1])
This will print:
Shortest name: Thanos
Longest name: Black Widow
Upvotes: 0
Reputation: 22134
The following code will identify the longest line in the numbers_file, and print it.
try:
longest_name = ''
with open("Marvel.txt") as numbers_file:
for line in numbers_file:
if len(line) > len(longest_name):
longest_name = line
print(longest_name)
Upvotes: 0