Well I am practicing slicing and want to run a program that prints a name backwards.

Mainly, I want to know how to access the last item in the sequence.

I wrote the following:

name = raw_input("Enter Your Name: ")
backname = ???

print backname

Does this look sound? Obviously, the ??? are not apart of my syntax, just asking what should go there. Thanks ahead of time!


You probably want to read the docs: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange

There's a method to reverse the string for you, if you want. For the specific question you asked, to access the last item of a sequence you use "seq[-1]".

+1  A: 
backname[-1] #the last item in the sequence

 #To reverse backname (the long way):
aList = [c for c in backname]  #will give you ['1', '2', ..., 'n']
aList.reverse()                #aList will be ['n', ..., '2', '1] 
backname = "".join(aList)      #backname reversed

 #To reverse backname, as other answers replied:
+1  A: 

To access the last item in a sequence, use:

print name[-1]

This is the same as:

print name[len(name) - 1]

Reversing a sequence has a common idiom in Python:

backname = name[::-1]

The Good primer for Python slice notation question has more complete information.

Greg Hewgill
+1  A: 

You want name[::-1]. The -1 is the "step" of the slice-- if you wanted every other letter, for example, you would use name[::2].

Tyler Durden
+1  A: 

You can use negative indices to access items counting from the end of a list, so name[-1] will give you the last character. However, the third slice argument is a step, which can also be negative, so this will give you the whole string in reverse:

Michael Mrozek

It does look sound. And your second line should be

backname = name[::-1]
+1  A: 

With slice syntax, you would use:

backname = name[::-1]

The two colons show that the first two parameters to the slice are left at their defaults, so start at the beginning, process to the end, but step backwards (the -1).