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

Asked

Viewed 199 times

11

I have the following expression:

namer = name[-4:]

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

1 answer

9


That’s a Slice (slice). The code in question returns the last four characters of the string.

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

  • When start is left blank it means "return everything from the beginning of the string".
  • When the end is left blank it 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".

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

Slicing can be used with other types besides string (e.g., a list), plus slicing has an optional third parameter for step increment (extended slice), but this is outside the scope of the question .

  • 1

    It would only make an addendum that a Slice can be [começo:fim:passo], the last parameter being the Slice jump. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.