1

I am practicing slicing, and I 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

Is this a sound approach? Obviously, the ??? is not a part of my syntax, just asking what should go there.

Kevin
  • 72,202
  • 12
  • 116
  • 152
TopChef
  • 40,537
  • 10
  • 26
  • 27
  • 1
    possible duplicate of [good primer for python slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) – Greg Hewgill Jul 07 '10 at 22:45

7 Answers7

3

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.

Community
  • 1
  • 1
Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
1
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:
 backname[::-1]
user347594
  • 1,226
  • 7
  • 11
1

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].

1

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:

name[::-1]
Michael Mrozek
  • 161,243
  • 28
  • 165
  • 171
1

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).

sunetos
  • 3,348
  • 22
  • 14
0

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]".

vanza
  • 9,247
  • 1
  • 30
  • 33
0

It does look sound. And your second line should be

backname = name[::-1]
tslak
  • 1