How to use only one character from the user input string In Python

This approach will use the string indexing to extract only a single required character from the user input.

Using only the first character of the string:

Python3




usrInput = input('Please enter a character:')[0]
print(f'Your single character input was: {usrInput}')


Output:

Please enter a character:adfs
Your single character input was: a

Using the ith character of the string:

Python3




i = 7
 
usrInput = input('Please enter a character:')[i]
print(f'Your single character input was: {usrInput}')


Output:

Please enter a character:0123456789
Your single character input was: 7

Using the last character of the string:

Python3




usrInput = input('Please enter a character:')[-1]
print(f'Your single character input was: {usrInput}')


Output:

Please enter a character:dfsg
Your single character input was: g

The time complexity of this code is constant, O(1), because the input string has only one character and the indexing operation to retrieve the last character takes constant time.

The space complexity is also constant, O(1), because the only memory used is for the variable usrInput, which stores a single character.



How to Take Only a Single Character as an Input in Python

Through this article, you will learn how to accept only one character as input from the user in Python.

Similar Reads

Prompting the user again and again for a single character

To accept only a single character from the user input:...

Using only one character from the user input string

...