In this tutorial, learn how to access string character by index using Python. Get a character from string and print in the output. Find the character within range and print all matching characters.
You can print single element by index or print all elements within range. Check each example given in this post to learn all about accessing string characters.
Access Single String Character By Index in Python
To find only the exact matching character from the string in Python. You have to use the indexing system which starts from zero(0).
The indexing system works within the square bracket(). You have to enter the required index whose character you want to print in the output.
str = "Hello World!"
The above example prints the second character of the string with 1 as the index. To print other string characters with this, you have to again mention the index with the number.
This example is for accessing the single element of the string. However, you can also access all the elements within the range. To perform this task, you have to read the next section of this post. So, keep reading this post to the end.
How to Get String Characters Within Range in Python
In order to get the string character within a certain range. You have to use the slice which works within the square bracket and colon(:). The first index value within the slice showing the starting point of the string character. The second value showing the end of the range which prints just its previous index character.
Check the example given below to find how it works within the range. You can change the range as per your requirement.
str = "Hello World!"
The above example prints the 4 characters from the start of the string. To print more characters, you have to increase the mentioned value in the range.
You may also like to read
- How to create a string variable in Python
- Limit float to two decimal places in Python
- Combine two string variables in Python
- How to change string to uppercase in Python
Hope, you like this tutorial of how to access string character by index in Python. If you have any query regarding the tutorial, please comment below.
- Stackoverflow Discussion on How to create a string variable in Python
- Python Doc on Common string operations
- Thispointer Tutorial on accessing Python string Characters
- RealPython Tutorial on String Character Data in Python
Also tell me, which method you are using to get the string character by index in Python.