How To Take A Character From A String In Python

In this tutorial, we will learn how to take a character from a string in Python. String manipulation is one of the most common tasks a programmer encounters in their day-to-day work. Python provides various options to achieve this task with ease. Let’s go through the steps.

Step 1: Defining the String

First, you need to define a string that will be manipulated. It can be a plain string or a string variable acquired from an input. For this tutorial, let’s define a simple string:

Step 2: Accessing Characters in String

Python strings are immutable sequences, meaning they cannot be changed after they are created. To access a character in a string, you can use indexing with square brackets. The syntax is string[index]. Keep in mind that indexing starts at 0.

For example, let’s access the second character in our string ("e"):

Output:

e

Step 3: Using Negative Indexing

Python also supports negative indexing, which allows you to access characters from the end of the string. The syntax is string[-index], with -1 being the index for the last character, -2 for the second to last character, and so on.

For example, let’s access the second last character in our string ("l"):

Output:

d

Step 4: Handling IndexError Exceptions

If you try to access a character beyond the length of the string, Python raises an IndexError exception. It is a good practice to handle this exception while accessing characters in a string.

For example, let’s try to access a character at index 20:

Output:

Index out of range

Now, let’s display the full code:

Output:

e
d
Index out of range

Conclusion

In this tutorial, we learned how to take a character from a string in Python using indexing and negative indexing. We also touched upon how to handle IndexError exceptions. These techniques are essential for working with strings in Python and will serve as a powerful tool in your programming toolbox.