How to Get the Nth Character in a String in Python
Get Nth Character in String
Given a string myStr
, we need to extract the character at a specific position, referred to as the Nth character.
To get the Nth character from a string in Python, we can use indexing. Indexing in Python starts at 0
, so the first character is at position 0
, the second at position 1
, and so on. To retrieve the Nth character, you need to access the character at index n-1
.
Syntax
The syntax of the expression to get the Nth character from string myStr
is:
myStr[n-1]
Here, n
is the position of the character (1-based index) to retrieve. Remember that indexing starts at 0
.
Example
In the following program, we take a string in myStr
and extract the third character (position 3
, index 2
).
Python Program
myStr = 'apple'
position = 3 # Third character (1-based position)
index = position - 1 # Convert to 0-based index
output = myStr[index]
print(f'Input String : {myStr}')
print(f'Character at Position {position} : {output}')
Output
Input String : apple
Character at Position 3 : p
Summary
In this tutorial of Python Examples, we learned how to extract the Nth character from a string using indexing. When accessing the Nth character, convert the position to a 0-based index by subtracting 1 from n
.