11
I have the following expression:
namer = name[-4:]
Where name
gets a name, but what does that mean [-4:]
?
11
I have the following expression:
namer = name[-4:]
Where name
gets a name, but what does that mean [-4:]
?
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
.
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 .
Browser other questions tagged python syntax
You are not signed in. Login or sign up in order to post.
It would only make an addendum that a Slice can be
[começo:fim:passo]
, the last parameter being the Slice jump. (:– Felipe Avelar