- Python: Get the First Character of String
- Get First Character of String in Python
- Python Program for First Character of String
- Get First Character of String using Slicing
- Python program to Get First Two Character of String
- Python Program for First Letter of String
- How to take only a single character as an input in Python
- Take only a single character as an input in Python
- Take only the first character from the user input in Python
- 3 responses to “How to take only a single character as an input in Python”
- Python input one character
- # Only allow letters when taking user Input using regex
- # Only allowing letters and spaces when taking user input
- # Additional Resources
Python: Get the First Character of String
Here, we will develop a Python program to get the first character of a string. If the string was “Knowprogram” then print the first character “K”. We will discuss how to get the first character from the given string using native methods, and slice operator. Also, we will develop a Python program to get the first two characters of a string.
Get First Character of String in Python
We will take a string while declaring the variables. Then, we will run the loop from 0 to 1 and append the string into the empty string (first_char). Finally, the first character will be displayed on the screen.
# Python Program get first character of string # take input string = input('Enter any string: ') # get first character first_char = "" for i in range(0, 1): first_char = first_char + string[i] # printing first character of string print('First character:', first_char)
Output for the different input values:-
Enter any string: Python
First character: P
Enter any string: Know Program
First character: K
Python Program for First Character of String
In python, String provides an [] operator to access any character in the string by index position. We need to pass the index position in the square brackets, and it will return the character at that index. As indexing of characters in a string starts from 0, So to get the first character of the given string pass the index position 0 in the [] operator i.e.
# Python Program get first character of string # take input string = input('Enter any string: ') # get first character first_char = string[0] # printing first character of string print('First character:', first_char)
Enter any string: character
First character: c
Get First Character of String using Slicing
We will get the first character of the string using the slice operator. The [:1] specifies the character at index 0. The string[:1] specifies the first characters of the given string.
# Python Program get first character of string # take input string = input('Enter any string: ') # get first character first_char = string[:1] # printing first character of string print('First character:', first_char)
Enter any string: first
First character: f
Python program to Get First Two Character of String
In the previous program, we will discuss how to get the first character of the string but in this program, we will discuss how to get the first two characters of the given string.
# Python Program get first two character of string # take input string = input('Enter any string: ') # get first two character first_two = string[:2] # printing first two character of string print('First character:', first_two)
Enter any string: Two character
First character: Tw
Python Program for First Letter of String
This python program is different from the above program, in this program, we will print all first characters of the given string. If the string was “Know Program” then print all first characters “KP”.
# Python Program get first character from a string # take input string = input('Enter any string: ') # get first character first_char = ''.join([s[:1] for s in string.split(' ')]) # printing first character of string print('First character:', first_char)
Output for the different input values:-
Enter any string: Know Program
First character: KP
Enter any string: First character of a string
First character: Fcoas
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!
How to take only a single character as an input in Python
In this tutorial, we will learn how to take only a single character as an input in Python with some cool and easy examples. In many situations, you might have to come up with this type of requirements.
I know you are here just because you are in need of this awesome trick to take only a single character as an input in Python ignoring all the characters entered by the user except the first character.
If you don’t know how to ignore all the characters of user input except the first character then you are at the right place. Because in this tutorial we gonna find out how to accept only first character as an user input in Python.
Take only a single character as an input in Python
Let’s learn this with some easy examples,
At first, create a variable which can hold the value entered by the user. ( user input )
user_input = input('Enter Your Characters\n') print(user_input)
Here \n is used just to create a new line so that it looks nice. If you wish you can omit it.
Run it online
If you run this program the output will be like this:
Now in the console log, you can enter characters and the characters will be stored in the variable user_input
to print only the first character. That will work fine.
But our main aim is to get the only first character as an input. But if we use the above code we can not achieve our goal. We are just printing the first character from the user input characters. But all the characters entered by the user is being stored in the user_input variable.
We need to find a way to store only the first character from the given input entered by the user in the console log.
The below code will help us to achieve our goal
user_input = input('Enter Your Characters\n')[0] print(user_input)
Run this code online
Now if you run the code it will ask you to enter characters. But it will not store all the characters in that variable. It will just store the first character from the user input entered by the user in the console log.
Suppose you run the above program and entered “ufayuyosuh” as an input. It will store only “u” in the variable.
user_input = input('Enter Your Characters')[n-1]
Here the n-1 surrounded with the square brackets is the index of the character entered by the user. You can change the value of n to store your required character. If you wish to take only the 3rd character from the input then use 2 instead of n-1. because of 3-1=2
Take only the first character from the user input in Python
user_input = input('Enter Your Characters\n')[0] print("\nYour variable is\n") print(user_input)
Enter Your Characters soikhdhskhsgjs Your variable is s
3 responses to “How to take only a single character as an input in Python”
Using the input function means having to terminate the string with a . Is there a means of reading a single character input via the keyboard in non-windows code? I’m using IDLE to run Python3 code.
character = input(“Enter a character\n”)[0]
vowels = “aeiou”
if character in vowels:
print(character)
Python input one character
If the user entered only letters, we print the input value and break out of the loop.
The break statement breaks out of the innermost enclosing for or while loop.
The input function takes an optional prompt argument and writes it to standard output without a trailing newline.
# Only allow letters when taking user Input using regex
Alternatively, you can use a regular expression.
Copied!import re user_input = '' while True: user_input = input('Enter letters only: ') if not re.match(r'^[a-zA-Z]+$', user_input): print('Enter only letters') continue else: print(user_input) break
The code snippet achieves the same result but uses a regular expression to validate the user input.
# Only allowing letters and spaces when taking user input
If you also want to allow spaces, use the following regular expression instead.
Copied!import re user_input = '' while True: user_input = input('Enter letters only: ') # 👇️ also allows spaces if not re.match(r'^[a-zA-Z\s]+$', user_input): print('Enter only letters') continue else: print(user_input) break
The re.match method returns a match object if the provided regular expression is matched in the string.
The match method returns None if the string does not match the regex pattern.
The first argument we passed to the re.match method is a regular expression.
The square brackets [] are used to indicate a set of characters.
The caret ^ matches the start of the string and the dollar sign $ matches the end of the string.
The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the letter ranges).
Copied!import re user_input = '' while True: user_input = input('Enter letters only: ') # 👇️ also allows spaces if not re.match(r'^[a-zA-Z\s]+$', user_input): print('Enter only letters') continue else: print(user_input) break
The \s character matches Unicode whitespace characters like [ \t\n\r\f\v] .
If the user didn’t enter only letters, we use the continue statement to prompt them for input again.
Otherwise, we use the break statement to break out of the while loop.
If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.
The page contains a list of all of the special characters with many useful examples.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.