"[-4:]" What is this syntax?

8

I have the following expression:

namer = name[-4:]

Where name gets a name, but what does this [-4:] mean?

    
asked by anonymous 05.11.2015 / 23:01

1 answer

6

This is a slice (slice). The code in question returns the last four characters of the string.

A slice follows the [começo:fim] pattern. começo and fim are indexes starting from zero. The character of the first index is included in the slice, since the last index character is not, i.e., the slice includes começo but does not include fim .

  • When start is left blank this means "return everything from the beginning of the string".
  • When the end is left blank this means "return everything to the end of the string".
  • When we put a negative sign in front of an index it means "count the number of characters from the end of the string instead of the beginning".

Then [-4:] means "return the slice from the fourth last index to the end of the string".

Slicing can be used with other types besides string (eg, a list), and slicing has an optional third parameter for incrementing the step ), but this is beyond the scope of the question.

    
06.11.2015 / 00:00