'how do I output a list of strings that fall alphabetically between two input values
I'm given a text file called input1.txt1
this file contains the following
aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists
Write a program that first reads in the name of an input file, followed by two strings representing the lower and upper bounds of a search range. The file should be read using the file.readlines() method. The input file contains a list of alphabetical, ten-letter strings, each on a separate line. Your program should output all strings from the list that are within that range (inclusive of the bounds).
EX:
Enter the path and name of the input file: input1.txt
Enter the first word: ammunition
Enter the second word (it must come alphabetically after the first word): millennium
The words between ammunition and millennium are:
aspiration
classified
federation
graduation
millennium
Solution 1:[1]
file_to_open = input()
bound1 = input()
bound2 = input()
with open(file_to_open) as file_handle:
list1 = [line.strip() for line in file_handle]
out = [x for x in list1 if x >= bound1 and x <= bound2]
out.sort()
print('\n'.join(map(str, out)))
Solution 2:[2]
Use a list comprehension with inequalities to check the string range:
out = [x for x in your_list if x >= 'ammunition' and x <= 'millennium']
This assumes that your range is inclusive on both ends, that is, you want to include ammunition
and millennium
on both ends of the range.
To further sort the out
list and then write to a file, use:
out.sort()
f = open('output.txt', 'w')
text = '\n'.join(out)
f.write(text)
f.close()
Solution 3:[3]
if you should use readline() try this :
filepath = 'Iliad.txt'
start = 'sometxtstart'
end = 'sometxtend'
apending = False
out = ""
with open(filepath) as fp:
line = fp.readline()
while line:
txt = line.strip()
if(txt == end):
apending = False
if(apending):
out+=txt + '\n'
if(txt == start):
apending = True
line = fp.readline()
print(out)
Solution 4:[4]
This worked for me:
file = input()
first = input()
second = input()
with open(file) as f:
lines = f.readlines()
for line in lines:
l = line.strip('\n')
if (l >= first) and (l <= second):
print(line.strip())
else:
pass
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | A.C |
Solution 2 | |
Solution 3 | Nilanka Manoj |
Solution 4 | mdia234 |