How to Input String in Python
Learn how to input string in Python, including the definition of strings and basic usage. …
Updated June 14, 2023
Learn how to input string in Python, including the definition of strings and basic usage.
Definition of Strings in Python
In Python, a string is a sequence of characters, such as words or phrases. Strings are an essential data type in Python programming. You can input strings using various methods, which we will cover in this article.
Step 1: Basic String Input
To input a string in Python, you use the input()
function. The input()
function returns a string that is entered by the user.
# Get user input and store it in a variable
user_input = input("Please enter your name: ")
print(user_input)
In this example:
- We call the
input()
function with a prompt message. - The
input()
function returns a string that is entered by the user. - We assign the returned string to the variable
user_input
. - Finally, we print out the input string using
print(user_input)
.
Step 2: Advanced String Input
You can also use the raw_input()
function (available in Python 2.x) or the built-in input()
function (available in Python 3.x) with a specific input format to get more complex input strings.
# Get user input using raw_input() and store it in a variable
user_input = raw_input("Please enter your name: ")
print(user_input)
# Get user input using input() and store it in a variable
user_age = int(input("Please enter your age: "))
print(user_age)
In this example:
- We call the
raw_input()
function (Python 2.x) or the built-ininput()
function (Python 3.x) with a prompt message. - The
raw_input()
function returns a string that is entered by the user, while theinput()
function returns an expression evaluated from the given input source. - We assign the returned string to the variable
user_input
or the integer value of the input string to the variableuser_age
. - Finally, we print out the input string using
print(user_input)
or the input integer value usingprint(user_age)
.
Step 3: Handling Empty String Input
If you want to handle empty string input, you can use a conditional statement to check if the user’s input is an empty string.
# Get user input and store it in a variable
user_input = input("Please enter your name: ")
if not user_input:
print("You didn't enter your name.")
else:
print(user_input)
In this example:
- We call the
input()
function to get the user’s input. - We check if the user’s input is an empty string using
not user_input
. - If the user’s input is an empty string, we print a message indicating that they didn’t enter their name.
- Otherwise, we print out the user’s input.
By following these steps and examples, you should now have a solid understanding of how to input strings in Python. Remember to use the input()
function to get user input and handle empty string inputs using conditional statements.