-3

I want to make a program that reads a text file from my directory and prints out the words backwards.

for example: My text file contains this sentance: "Others follow the British historian A. J. P. Taylor"

using this code:

f=open('c:/Python27/ww2.txt','r')
print f.readline()

it will print this: "Others follow the British historian A. J. P. Taylor"

What I want to print is this: "rolyaT .P.J.A niarotsih hsitirB eht wollof srethO"

How can I accomplish this?

  • 2
    Gee, if only there was a way to have `sorted` lists and then `reverse` them in Python.... –  Jan 22 '15 at 21:16
  • possible duplicate of [Reverse a string in Python](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) –  Jan 22 '15 at 21:34
  • possible duplicate of [Read a file in reverse order using python](http://stackoverflow.com/questions/2301789/read-a-file-in-reverse-order-using-python) – alvas Jan 22 '15 at 21:43

2 Answers2

3
print f.readline()[::-1]

This is a duplicate of reverse a string in Python

Community
  • 1
  • 1
MrAlexBailey
  • 5,219
  • 19
  • 30
0

If I understood your question, just use reverse string indexing. it should look like this:

s="Whatever"
print s[::-1]

It will then print s backwards

Chris Nguyen
  • 160
  • 1
  • 4
  • 14