Skip to content

Python find last character in string | Example code

  • by

The best and easy way to find the last character in a string is negative indexing. Every character in a string has an index number associated that can be a positive or negative number.

Python find the last character in a string example

Simple example code selects the last element using the negative index, i.e. -1.

sample_str = 'Hello World'
print(sample_str[-1])

Output:

Python find the last character in a string

Return the last character of string in python

If the given string is multiline then it last character of every line is a newline character. We have to clear its leading and trailing spaces. Then return the last character in your case.

Use the strip method in this case.

sample_str = 'Hello   World ' \
             ''
print(sample_str.strip()[-1])

Output: d

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

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