To get the last character in a string using Python, the easiest way is to use indexing and access the “-1” position of the string.

string = "This is a string."

last_character = string[-1]

print(last_character)

#Output:
.

When working with strings, it can be valuable to be able to easily filter and get only specific values from your list.

One such situation where you may want to get only the last character of a string.

In Python, we can easily get the last character of a string using string indexing.

Below shows how we can use indexing in Python to get the last character in a string.

string = "This is a string."

last_character = string[-1]

print(last_character)

#Output:
.

Getting the Last n Characters from a String in Python

In Python, we can easily get the last n characters in a string. To get the last n characters of a string, we can use slicing.

Below is a basic example in Python of how to get the last n characters from a string. We will use 3 for n.

string = "This is a string."

last_3_characters = string[-3:]

print(last_3_characters)

#Output:
ng.

Getting the First Character in a String Using Python

We can modify our first example to easily be able to access the first character of a string in Python.

Python strings start with a zero index, and so to get the first character of a string, we can access the “0” position.

Below is a basic example in Python of how to get the first character of a string.

string = "This is a string."

first_character = string[0]

print(first_character )

#Output:
T

Hopefully this article has been useful for you to understand how to get the last character in a string using Python.

Categorized in:

Python,

Last Update: March 18, 2024