CharAt in Python

CharAt in Python

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:

Output:

J

Similarly, you can access 4th char of String as below:

Output:

a

Here is image which will help you understand alternative of charAt in Python.
Python charAt

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

Here is simple java code snippet:

Output:

First character of String Java2blog is : J

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.

Output:

H

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.

Output:

J
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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *