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:
givenString[index]
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.