charAt in Python

In this post, I will be sharing the Python equivalent of charAt() in Java. Every method that is defined in Java has its alternative in Python. Similarly, charAt() method in Java that is utilized to return a character from a string at the specified index has its Python equivalent too. In Python, characters of a string can be accessed just like how you do it with elements of an array in Java and lists in Python.

In short,

givenString = "ALIVE IS AWESOME"
var = givenString[0]   # charAt(0), which is 'A' in this case

Read Also: Convert list to set in Python

Let's dive deep into the charAt() method in Java and how we can get similar functionality in Python.

charAt(index) in Java example

The syntax of charAt method is given below:

char charVariable = str.charAt(int index)

The example of the charAt() method in Java is shown below:

public class CharAtExample 
        public static void main(String args[]) // This is referred to as the main method
        String givenString = "HELLO JAVA"; 
        char charVariable = givenString.charAt(1); // We have to get the character at index->1 in the givenString 
        System.out.println(charVariable); // Printing the character charVariable 

Output: E

Python Code

Oh, it's too lengthy. So, let's reduce the code and see how easy and beautiful the python code looks!. But before that, we need to understand what is a subscript operator in Python.

What is a subscript operator in Python?

The subscript operator in Python is square brackets i.e [].

The syntax of the subscript operator looks like this:


In Python, we will use an array subscript with the starting character having an index of zero. Below is the Python code block for the Java code above.

givenString = "HELLO PYTHON"  
charVariable = givenString[1] #This is the syntax to access a character from the givenString
print(charVariable) #Prints the character

Output: E

That's all for today, please mention in the comments in case you have any questions related to charAt in Python.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry