Table of Contents
In this tutorial, we will see about CharAt in Python.
If you are already well verse in java and might be looking for charAt()
alternative in Python, then you are at right place.
In Python, you can get character of String similar to the way you access array elements in java.
Here is simple code snippet to give you an simple example:
1 2 3 4 5 6 |
str="Java2blog" firstChar=str[0] // Prints first character of String print(firstChar) |
Output:
Similarly, you can access 4th char of String as below:
1 2 3 4 5 6 |
str="Java2blog" fourthChar=str[3] // Prints first character of String print(fourthChar) |
Output:
Here is image which will help you understand alternative of charAt in Python.
CharAt() in java
charAt() method in java is used to access character of String by its index. You need to pass index of the character that you want to retrieve.
Syntax
1 2 3 |
Char chr = str.charAt(index); |
Here is simple java code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class ChatAtJavaMain { public static void main(String[] args) { String str="Java2blog"; char c = str.charAt(0); System.out.println("First character of String Java2blog is : "+c); } } |
Output:
Alternative of charAt() in Python
As you an see, java has charAt()
method specifically for accessing character of String, but in Python, you can just use subscript operator to access character of String. It’s syntax is similar to the way you access elements of array in java.
Subscript operator is nothing, but square bracket([]) and you need provide index of the element that you want to access.
1 2 3 4 5 6 |
str="Hello world" firstChar=str[0] // Prints first character of String print(firstChar) |
Output:
Further reading:
Iterate through String and print its character
Let’s now right a program to iterate through String and print its character using altearative of charAt() in Python.
1 2 3 4 5 6 7 |
str = "Java2blog" i = 0 while i < len(str): print (str[i]) i += 1 |
Output:
a
v
a
2
b
l
o
g
As you can see, we have used while loop to iterate through String and subscript operator to access each character of String using its index.
That’s all about charAt in Python.