Display last character of a string

In this blog, we will create a python program to display last character in a string.
Each character in a string can be accessed by its index number. Below is the string with index position of each character.

String                     P    y    t     h    o    n
Index number      0    1    2    3     4    5
Index number always start with 0. First character in a string has index position of 0, second character in a string has index position of 1 and so on.
Below is the logic to display last character of a string.
  1. Use len() function to find length of a string or number of characters in a string.
  2. Subtracting 1 from total length of  a string to get index position of last character.
  3. Displaying the last character.
Getting string from user.
str = input('Please enter any string: ')
Calculating length of string.
length = len(str)
Display total length of  a string
print('Total length of a string:%s'%length)
Subtracting 1 from total length of  a string. Variable last_char holds index postion of last character.
last_char = length - 1
Display last charater of a string.
print('Last character in a string:%s'%str[last_char])
OUTPUT
Please enter any string: Navigate
Total length of a string:8
Last character in a string:e
Complete Code
str = input('Please enter any string: ')
length = len(str)
print('Total length of a string:%s'%length)
last_char = length - 1
print('Last character in a string:%s'%str[last_char])

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s