Skip to content

Get last two characters of string Python | Example code

  • by

Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.

string

[length-2:]

Example Get last two characters of string in Python

Simple example code. It will slice the starting char excluding the last 2 characters.

str1 = "Hello world"
l = len(str1)
print(str1[l - 2:])

Output:

Get last two characters of string Python

Get the last character of string using len() function

Calculate string length first and then access character at length -1.

str1 = "Hello world"
l = len(str1)
print(str1[l - 1])

Output: d

Do comment if you have any doubts and suggestions on this Python char code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading