How to Print the Nth Character in a String in Python
Print Nth Character in String
Given a string myStr, we need to print the character at a specific position, referred to as the Nth character.
To print the Nth character from a string in Python, we can use indexing. Since indexing in Python starts at 0, the character at position n (1-based) is accessed using index n-1.
Syntax
The syntax of the expression to print the Nth character from string myStr is:
print(myStr[n-1])Here, n is the position of the character (1-based index) to print. Remember that indexing starts at 0.
Example
In the following program, we take a string in myStr and print 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
print(f'Input String : {myStr}')
print(f'Character at Position {position} : {myStr[index]}')
Output
Input String : apple
Character at Position 3 : pSummary
In this tutorial of Python Examples, we learned how to print the Nth character from a string using indexing. When printing the Nth character, convert the position to a 0-based index by subtracting 1 from n.