To get the first character of a string using Python, the easiest way is to use indexing and access the “0” position of the string.

string = "This is a string."

first_character = string[0]

print(first_character)

#Output:
T

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 first character of a string.

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

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

string = "This is a string."

first_character = string[0]

print(first_character)

#Output:
T

Getting the First n Characters from a String in Python

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

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

string = "This is a string."

first_3_characters = string[:3]

print(first_3_characters)

#Output:
Thi

Getting the Last Character in a String Using Python

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

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.

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

string = "This is a string."

last_character = string[-1]

print(last_character)

#Output:
.

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

Categorized in:

Python,

Last Update: March 20, 2024