32

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?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Swen Kooij
  • 985
  • 1
  • 8
  • 18

5 Answers5

65

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]
Community
  • 1
  • 1
9

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.

Community
  • 1
  • 1
4

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] 
jackcogdill
  • 4,900
  • 3
  • 30
  • 48
0

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

See the tutorial.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

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.

poke
  • 369,085
  • 72
  • 557
  • 602