1 mean in python?

Possible Duplicate:
The Python Slice Notation

I'm trying to port some Python code to C, but I came across this line and I can't figure out what it means:

if message.startswith('<stream:stream'):
    message = message[:-1] + ' />'

I understand that if ' message starts with <stream:stream then something needs to be appended. However I can't seem to figure out where it should be appended. I have absolutely no idea what :-1 indicates. I did several Google searches with no result.

Would somebody be so kind as to explain what this does?


It is list indexing, it returns all elements [:] except the last one -1 . Similar question here

For example,

>>> a = [1,2,3,4,5,6]
>>> a[:-1]
[1, 2, 3, 4, 5]

It works like this

a[start:end]

>>> a[1:2]
[2]

a[start:]

>>> a[1:]
[2, 3, 4, 5, 6]

a[:end]
Your case

>>> a = [1,2,3,4,5,6]
>>> a[:-1]
[1, 2, 3, 4, 5]

a[:]

>>> a[:]
[1, 2, 3, 4, 5, 6]

It's called slicing, and it returns everything of message but the last element.

Best way to understand this is with example:

In [1]: [1, 2, 3, 4][:-1]
Out[1]: [1, 2, 3]
In [2]: "Hello"[:-1]
Out[2]: "Hell"

You can always replace -1 with any number:

In [4]: "Hello World"[:2] # Indexes starting from 0
Out[4]: "He"

The last index is not included.


It's called slicing

"Return a slice object representing the set of indices specified by range(start, stop, step)."
-from this link: http://docs.python.org/2/library/functions.html#slice

You'll notice it's similar to the range arguments, and the : part returns the entire iterable, so the -1 is everything except the last index.

Here is some basic functionality of slicing:

>>> s = 'Hello, World'
>>> s[:-1]
'Hello, Worl'
>>> s[:]
'Hello, World'
>>> s[1:]
'ello, World'
>>> s[5]
','
>>>

Follows these arguments:

a[start:stop:step]

Or

a[start:stop, i] 
链接地址: http://www.djcxy.com/p/26736.html

上一篇: 从列表中获取第一个x项目

下一篇: 1在Python中的意思?