Iterate file line by line and reverse each before printing.
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
As Tony stated, you can iterate over a file
#f = open('lorumipsum.txt');
# simulate the file
f=["Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim\n",
"veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit\n",
"esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit\n",
"anim id est\n",
"laborum\n"]
for rec in f:
print rec[::-1] ## using slicing to reverse
# but you can also do it with a loop
for rec in f:
reversed_list = []
for ctr in range(len(rec)-1, -1, -1): ## go from last letter to the first
## string concatenation is slow and expensive
## append to a list and join()
reversed_list.append(rec[ctr])
print "".join(reversed_list)
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
If you google "reversing a string in python," you'd find that stackoverlfow has a nice answer ( http://stackoverflow.com/questions/931092/reverse-a-string-in-python ). So, for your code, we can do, and test:
str1 = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum'''.replace(' ', '')
str2 = '''murobal
tse di mina tillom tnuresed aiciffo iuq apluc ni tnus ,tnediorp non tatadipuc taceacco tnis ruetpecxE .rutairap allun taiguf ue erolod mullic esse
tilev etatpulov ni tiredneherper ni rolod eruri etua siuD .tauqesnoc odommoc ae xe piuqila tu isin sirobal ocmallu noitaticrexe durtson siuq ,mainev
minim da mine tU .auqila angam erolod te erobal tu tnudidicni ropmet domsuie od des ,tile gnicisipida rutetcesnoc ,tema tis rolod muspi meroL'''.replace(' ', '')
print str1[::-1] == str2 # Evaluates as True.
I removed the whitespace because there might've been a discrepancy between the output you got and the text pasted into the the daniweb editor. Though, I don't see why the code wouldn't work with whitespace as well.
Thisisnotanid
Junior Poster in Training
60 posts since Dec 2010
Reputation Points: 10
Solved Threads: 0