What does :-1 mean in python?

Question:

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?

Asked By: Swen Kooij

||

Answers:

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] 
Answered By: jackcogdill

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]
Answered By: user1786283

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

See the tutorial.

Answered By: NPE

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.

Answered By: user1632861

To answer your case directly:

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

This basically checks, if message starts with <stream:stream, and if that is the case it will drop the last character and add a ' />' instead.

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

Answered By: poke
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.