TopChef
TopChef

Reputation: 45513

How do I slice a sequence to get the last item?

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.

Upvotes: 1

Views: 469

Answers (7)

user347594
user347594

Reputation: 1296

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]

Upvotes: 1

sunetos
sunetos

Reputation: 3508

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

Upvotes: 1

tslak
tslak

Reputation: 1

It does look sound. And your second line should be

backname = name[::-1]

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175745

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]

Upvotes: 1

Tyler Durden
Tyler Durden

Reputation: 11

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

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994817

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.

Upvotes: 3

vanza
vanza

Reputation: 9903

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

Upvotes: 0

Related Questions