Get last two characters of string Python | Example code

Use lice 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 chrachers.

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.