开发者

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.


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.


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


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]


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


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]


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


It does look sound. And your second line should be

backname = name[::-1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜