Python String Indexing - How to Get Individual Characters

Learn how to get the individual characters of a string in Python using String Indexing.

Python String Indexing - How to Get Individual Characters

Welcome! ๐Ÿ‘‹ In this article, you will learn how to get an individual character from a Python string. This is especially helpful when you need to check or remove specific characters from a string you take as user input.

Are you ready? Let's begin! โœจ

๐Ÿ”น Strings Behind the Scenes

Before we start diving into string indexing, let's have a very quick review of strings and what they are in Python.

In a computer program, we often need to represent text to store or process real-world information, such as names, usernames, passwords, user input, and basically anything that can be represented as a sequence of characters. That's were strings come to our rescue. We use them to represent text in our code.

They sound very important, right? ๐Ÿ˜

That is why the creators of Python decided to incorporate String as a built-in data type. This means that it comes pre-defined in the programming language with its own characteristics, attributes, and operations, so you can work with strings directly in your programs.

Let's see how you can define a string in Python.

Defining a String

To define a string, you just need to surround it with single or double quotes.

This is an example:

"Hello, World!"
๐Ÿ’ก
It's important to use single or double quotes consistently. If you mix them in the same string, you will get an error because Python will not be able to know where the string ends.

You can think of strings as sequences of characters. They are immutable, which means that you cannot change their characters after they are defined in your program.

String Structure and Indices

Behind the scenes, we can think of strings as having an internal "Grid", where each character from left to right has a specific integer that identifies its position.

This integer is called an "index". We can use the index to access its corresponding character.

๐Ÿ’ก
You may find two plural versions of the word index: "indices" or "indexes". They are both commonly used.

In the diagram below, you can see an example of the internal "grid" for the string "Code":

You may have noticed from this diagram that indices start from 0 in Python.

This is very important and something that may take you some time to get used to because you need to start "counting" the indices from 0 instead of 1. Initially, this may seem counterintuitive. I know, I was there too.

But don't worry! I promise you that with time and practice, you will master it. ๐Ÿ˜

Basically, you start counting from 0 and then, as you move towards the right, you increment the index by 1 for every single character in the string (Yes, it's that easy!).

And why are indices so important? Well... Because we can use the indices of a string to get its individual characters.

๐Ÿ”ธ String Indexing in Python

Syntax

But how do we go from the index to actually getting the character itself? We use string indexing! ๐Ÿ‘€

To get the character located at a specific index, we write the variable that stores the string followed by the index surrounded by square brackets, like this:

string[index]

The square brackets are essential here because they tell Python:

"Hey! I'm going to get something from this sequence of characters. I will tell you what I need within the square brackets."

And how do you tell the program what you need? You do this by writing the index within the square brackets.

Here we have an example. I'm defining a variable and assigning a string to that variable.

my_string = "Code"

And this is a small diagram I made using comments ๐Ÿ˜Ž:

        "C o d e"
# Index  0 1 2 3

If we need to get the character at index 2, we would write:

  • my_string, the variable that stores the string.

  • An opening square bracket.

  • The integer 2 to represent the index.

  • A closing square bracket.

You can see this below:

my_string[2]
๐Ÿ’ก
You should write the opening square bracket immediately after the variable, without any spaces in between.

Using the Character

Then, once you have this expression to get the character that you need, you can work with it in your program. For example, you could assign it to a variable, print it, add it to a data structure, or anything else. The character will be of the data type String.

๐Ÿ’ก
Yes! A string can have just one character and it will still be a string. Curious, right? ๐Ÿค”

If you need to print the character, you can write something like this:

print(my_string[2])

The output would be a single character, the character at that index:

'd'

Remember, this is the general syntax for String Indexing in Python:

string[index]
๐Ÿ’ก
With this syntax, we are only getting one character but we can also get multiple characters if we need to. This technique is called String Slicing. ๐Ÿž
๐Ÿ’ก
Here, we are using the integer 2 directly for the examples, but you can also use a variable as the index to assign and update the value dynamically. This is what we usually do in real-world applications.

๐Ÿ”น Practice Question

Awesome. Now that you know how to get a character from a string, here is a quick quiz to help you review. ๐Ÿ’ก

We have a string with multiple characters. It has more characters than our previous examples but each character will still have its own index and the same rules will apply.

๐Ÿ’ก
Spaces and special characters have their own place in the grid, so they also count for the indices.

Try to guess the output of the following lines of code (before running the code! ๐Ÿ˜‰):

hello_world = "Hello, World"

print(hello_world[0])
print(hello_world[3])
print(hello_world[6])
print(hello_world[-1])
print(hello_world[257]) # This one is very interesting!

Try this before moving on and I will see you in just a moment...

๐Ÿ’ก
A few minutes later... โฐ

Hi! We are back. If you tried to guess the output, you may be curious to know more about the last two lines of code, right?

Let's see them in more detail.

๐Ÿ”ธ Negative Indices

There is something a bit different in this line of code, right?

print(hello_world[-1])

We have not used negative indices before.

Is this valid?

The short answer is YES.

It's completely valid to use a negative index, as long as it is in the valid range of indices for that string.

Let's illustrate this with an example. Below you can see a diagram with the corresponding negative indices for each character of this string.

But notice something curious... ๐Ÿค”

Now we start to count from right to left and we decrement the value by 1 as we move towards the left.

This applies to all Python strings, so if you ever need to get the last character of a string, you can just index -1 and avoid making any complicated calculations with the string length.

That's awesome, right? ๐Ÿ˜

๐Ÿ’ก
Yes, if you are thinking that every character actually has two indices instead of just one, you are correct. We can use its positive index or its negative index and we will still get the same character.

๐Ÿ”น String Index Out of Range

That was interesting, right?

Now let's solve the mystery of what happened with the last line of code. ๐Ÿ”ฎ

print(hello_world[257])

You must have seen something very similar to this if you ran your code:

IndexError: string index out of range

This error is very common, especially when we start working with strings.

It's telling us that the index we are using is not in the valid range of values for that particular string.

In this example, the valid range of indices would go from 0 to 3 (inclusive) because the string has four characters. Any index less than 0 or greater than 3 would be invalid.

        "C o d e"
# Index  0 1 2 3
๐Ÿ’ก
Here's a helpful tip: the last positive index will be the string length minus 1. If the string has four characters, the last positive index will be 3.

If you ever get this error, you just need to check the index you are using and update it to one of the valid values.

๐Ÿ”ธ Importance of String Indexing

String indexing can be super helpful for many different real-world applications, including:

  • Extracting characters for data cleaning.

  • Validating user input, such as passwords and phone numbers.

  • Text processing, like removing punctuation marks from a string.

  • Text formatting, like capitalizing strings.

  • Parsing CSV data.

And much more! String indexing can be helpful whenever you work with strings in Python and that is... almost always. ๐Ÿ˜Ž

๐Ÿ”น Summary

  • String indexing is used for getting an individual character from a Python string.

  • This is the basic syntax: variable[index], where variable is the variable that stores the string.

  • Indices are integers that identify the characters in the string.

  • There is a valid range of integers for each string, based on how many characters it has. If you use an index that is out of range, you will get an error.

  • You can use positive or negative indices to get the characters of a string.

Thank you so much for reading my article! ๐Ÿ˜Š To find more coding tips and tutorials, follow me on YouTube (Coding with Estefania) and X (@EstefaniaCassN).

Have an awesome day. ๐Ÿ”…

ย