vendredi 17 avril 2015

how to do a echo function to a file's last word in python

The detailed question is : Write a function that takes a single string representing a filename as an argument and a number, x. Open the file and use a while loop to build and return a string containing the phrase from the file and the last word x times. Note the new lines.



def echo(filename, x):
"""
>>> echo("phrase.txt", 2)
'Hello World!\\nWorld!\\nWorld!\\n'
>>> echo("phrase.txt", 4)
'Hello World!\\nWorld!\\nWorld!\\nWorld!\\nWorld!\\n'
"""

if __name__=="__main__":
import doctest
doctest.testmod(verbose=True)


what Im trying to do is:



def echo(filename,x):
files=open(filename,"r")
text=files.read()
filelist=text.split()
last_word=filelist[len(filelist)-1]
n=len(last_word)
count=last_word
while n<n*x:
count=count+last_word
n=n+1
return count


but unfortunately, this is not gonna work. as a new fish who still struggling in python, I really need somebody to give me a hand.


Aucun commentaire:

Enregistrer un commentaire