I have an assignment where I have a text file with a word on each line which forms a string. On some lines there are a number with which amount of times I have to print the string, separated by a comma and space and finish with a period
For instance:
Darth
Maul
is
a
bad
person
3
Which should then be: Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.
So far I'm quite stuck, I'm familliar with how to read the file line by line and I guess I have put the words in a list and determine when the number comes to iterate that list a number of times.
So far I have:
TEXT = input 'sith.txt'
words = []
with open(TEXT, 'r') as f:
line = f.readline()
for word in line:
if string in word //is a string not an int
words.append(string)
else //print words + ', '
After this I'm pretty much stuck. Anyone out there that could point me in the right direction?
You can use joins and the end argument in print to accomplish this with a fewer number of lines.
lines = open("input.txt", "r").read().splitlines()
data, number = " ".join(lines[:-1]), int(lines[-1])
print(", ".join([data]*number), end=". ")
Which outputs:
Darth Maul is a bad person, Darth Maul is a bad person, Darth Maul is a bad person.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With