What does it mean: -1 in python?

Possible duplicate:
Python snippet designator

I am trying to port some Python code to C, but I came across this line and I cannot figure out what this means:

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

I understand that if the ' message starts with <stream:stream , then something needs to be added. However, I cannot figure out where it should be added. I do not know what it means :-1 . I performed several google searches without any results.

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

+8
python syntax
source share
5 answers

This is an index of the list, it returns all the elements [:] , with the exception of the last -1 . Similar question here

For example,

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

It works as follows

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] 
+18
source share

It is called slicing, and it returns all message , but the last element.

The best way to figure this out with an 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]: "Hel" 
+3
source share

It's called slicing

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

You will notice that this is similar to the range arguments, and the part : returns the entire iterable object, so -1 is all but the last index.

Here are some basic slicing features:

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

Performs the following arguments:

 a[start:stop:step] 

or

 a[start:stop, i] 
+1
source share

It returns message without the last element. If message is a string, message[:-1] returns the last character.

See the tutorial .

0
source share

To answer your question directly:

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

This basically checks if message starts with <stream:stream , and if so, it will discard the last character and add ' />' instead.

So, since your message is an XML string, it will make the element an empty element, closing itself.

0
source share

All Articles