Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and print string x times

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?

like image 265
Thomas Bengtsson Avatar asked Dec 31 '25 01:12

Thomas Bengtsson


1 Answers

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.

like image 166
Grant Williams Avatar answered Jan 01 '26 16:01

Grant Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!