How can I get last 4 characters of a string in Python?


The slice operator in Python takes two operands. First operand is the beginning of slice. The index is counted from left by default. A negative operand starts counting from end. Second operand is the index of last character in slice. If omitted, slice goes upto end.

We want last four characters. Hence we count beginning of position from end by -4 and if we omit second operand, it will go to end.

>>> string = "Thanks. I am fine"
>>> string[-4:]
'fine'


Updated on: 20-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements