Tuesday, December 13, 2022

[FIXED] What does :-1 mean in python?

Issue

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?


Solution

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
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.