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 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
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
Input Validation in Python String In Python, string input validation helps ensure that the data provided by the user or an external source is clean, secure and matches the required format. In this article, we'll explore how to perform input validation in Python and best practices for ensuring that strings are correctly validated.Pyt
2 min read
Insert a Variable into a String - Python The goal here is to insert a variable into a string in Python. For example, if we have a variable containing the word "Hello" and another containing "World", we want to combine them into a single string like "Hello World". Let's explore the different methods to insert variables into strings effectiv
2 min read
List As Input in Python in Single Line Python provides several ways to take a list as input in Python in a single line. Taking user input is a common task in Python programming, and when it comes to handling lists, there are several efficient ways to accomplish this in just a single line of code. In this article, we will explore four com
3 min read
Insert a number in string - Python We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
2 min read
Iterate over words of a String in Python In this article, weâll explore different ways to iterate over the words in a string using Python.Let's start with an example to iterate over words in a Python string:Pythons = "Learning Python is fun" for word in s.split(): print(word)OutputLearning Python is fun Explanation: Split the string into w
2 min read
Convert JSON to string - Python Data is transmitted across platforms using API calls. Data is mostly retrieved in JSON format. We can convert the obtained JSON data into String data for the ease of storing and working with it. Python provides built-in support for working with JSON through the json module. We can convert JSON data
2 min read