How to take string as input from a user in Python
Last Updated :
26 Nov, 2024
Accepting input is straightforward and very user-friendly in Python because of the built-in input()
function. In this article, we’ll walk through how to take string input from a user in Python with simple examples.
The input()
function allows us to prompt the user for input and read it as a string. By default, whatever we type in the input prompt is stored as a string. Here’s how we can use it:
Python
n = input("Enter your name: ")
print("Hello,", n)
Explanation: The input("Enter your name: ") line displays a prompt for the user to enter their name. The entered string is stored in the variable name. print("Hello,", name) outputs the entered string along with the greeting.
Let's take a look at other cases of taking string as input:
Taking Input Splits, Space-Separated Strings
When taking string input from users, you might need to process the input in various ways, such as splitting it by default spaces, handling space-separated input, or using a custom delimiter for separation. Here, we'll cover all these methods with a single example.
Python
# Taking input from the user
s1 = input("Enter your input (e.g., 'apple banana cherry' or 'apple,banana,cherry'): ")
# 1. Default split (splits by whitespace)
sp = s1.split()
print("Default split (by whitespace):", sp)
# 2. Space-separated input
ss = s1.split(' ')
print("Split by space:", ss)
# 3. Custom delimiter input (comma-separated in this case)
sc = s1.split(',')
print("Split by comma:", sc)
Output:
Enter your input (e.g., 'apple banana cherry' or 'apple,banana,cherry'): apple banana cherry, abc efg
Default split (by whitespace): ['apple', 'banana', 'cherry,', 'abc', 'efg']
Split by space: ['apple', 'banana', 'cherry,', 'abc', 'efg']
Split by comma: ['apple banana cherry', ' abc efg']
Explanation: split() without arguments breaks the string based on whitespace. split(' ') specifically targets spaces as delimiters. split(',') demonstrates splitting the input string based on a custom delimiter (comma).
Note: You can add delimiters in spilt() to take input in the way you want to take from the user. It will split the string by the given delimiter.
To accept multiple string inputs, we can use multiple input()
calls. This way we can accept and manipulate multiple pieces of data entered by the user.
Python
f = input("Enter your first name: ")
l = input("Enter your last name: ")
print("Your full name is:", f, l)
Here, we prompt the user twice to input their first and last names separately. We print the combined result.
Although input()
always returns a string, we can easily convert the input to other types using functions like int()
, float()
, or bool()
. For example:
Python
age = input("Enter your age: ")
# Convert string to integer
#If the user enters something that is not a valid integer (e.g., a letter), it will raise a ValueError.
age = int(age)
print("In 10 years, you will be", age + 10, "years old.")
The input() function reads user input as a string. The int() function converts the string to an integer. The program then adds 5 to the user's age and prints a future age calculation.
Similar Reads
How to Take a List as Input in Python Without Specifying Size?
In many situations, we might want to take list as input without knowing the size in Python beforehand. This approach provides flexibility by allowing users to input as many elements as they want until a specified condition (like pressing Enter) is met. Letâs start with the most simple method to take
2 min read
How to Take Array Input in Python Using NumPy
NumPy is a powerful library in Python used for numerical computing. It provides an efficient way to work with arrays making operations on large datasets faster and easier. To take input for arrays in NumPy, you can use numpy.array. Taking Array Input Using numpy.array()The most simple way to create
3 min read
How to Initialize a String in Python
In Python, initializing a string variable is straightforward and can be done in several ways. Strings in Python are immutable sequences of characters enclosed in either single quotes, double quotes or triple quotes. Letâs explore how to efficiently initialize string variables. Using Single or Double
2 min read
How to change any data type into a String in Python?
In Python, it's common to convert various data types into strings for display or logging purposes. In this article, we will discuss How to change any data type into a string. Using str() Functionstr() function is used to convert most Python data types into a human-readable string format. It is the m
3 min read
How to format a string using a dictionary in Python
In Python, we can use a dictionary to format strings dynamically by replacing placeholders with corresponding values from the dictionary. For example, consider the string "Hello, my name is {name} and I am {age} years old." and the dictionary {'name': 'Alice', 'age': 25}. The task is to format this
3 min read
How to find length of a string in Python
In this article, we will learn how to find length/size of a string in Python. To find the length of a string, you can use built-in len() method in Python. This function returns the number of characters in the string, including spaces and special characters. [GFGTABS] Python s = "GeeksforGeeks
2 min read
How to Create String Array in Python ?
To create a string array in Python, different methods can be used based on the requirement. A list can store multiple strings easily, NumPy arrays offer more features for large-scale data and the array module provides type-restricted storage. Each method helps in managing collections of text values
2 min read
How to Use Words in a Text File as Variables in Python
We are given a txt file and our task is to find out the way by which we can use word in the txt file as a variable in Python. In this article, we will see how we can use word inside a text file as a variable in Python. Example: Input: fruits.txt apple banana orange Output: apple = Fruit banana = Fru
3 min read
How to Check if a Variable is a String - Python
The goal is to check if a variable is a string in Python to ensure it can be handled as text. Since Python variables can store different types of data such as numbers, lists or text, itâs important to confirm the type before performing operations meant only for strings. For example, if a variable co
3 min read
How To Convert Comma-Delimited String to a List In Python?
In Python, converting a comma-separated string to a list can be done by using various methods. In this article, we will check various methods to convert a comma-delimited string to a list in Python. Using str.split()The most straightforward and efficient way to convert a comma-delimited string to a
1 min read