Python String Input Output
Last Updated :
02 Apr, 2024
Python's print() method is used to show program output, whereas the input() function is used for collecting user input. Python starts to accept all input as strings; other data types require specific conversion. We will learn the fundamental input/output processes in Python in this tutorial. We'll talk about many uses of the Python programming language's input and output features in this section.
Python String Input Output Operation
Below, we will discuss the Python String Input Output operation in these two sections:
- Input Operation in Python
- Output Operation in Python
Input Operations in Python
As programmers, we sometimes have to provide the computer input while we are writing our code. Python's input() method may be used for this. When the user enters data, the input() method always returns a string data type. If we want to change the data type of our inputs, we have to use a different conversion method.
Example 1: String Input in Python
The input() method in Python allows you to get user-supplied string input. The input() method asks the user to enter a string and returns the result as a string. In this example, the below code takes the user to input their name and stores it in the variable "name". Then, it prints out the entered name with a descriptive message.
Python3
# Prompt the user to enter a string
name = input("Enter your name: ")
# Display the input string
print("You entered:", name)
Output
Enter your name: Pratham
You entered: Pratham
Example 2: Type Conversion For Input Operations
In Python, type conversion can be used to transform user input from one data type to another. This is useful when you need to get a data type (for example, integer or float) and perform operations on it. Here's how you can do input operations using type conversion:
Python3
# Accept the length of the rectangle from the user
length = float(input("Enter the length of the rectangle: "))
print("Length of the rectangle:", length)
# Accept the width of the rectangle from the user
width = float(input("Enter the width of the rectangle: "))
print("Width of the rectangle:", width)
# Calculate the area of the rectangle
area = length * width
# Print the area of the rectangle
print("Area of the rectangle:", area)
Output
Enter the length of the rectangle: 90
Length of the rectangle: 90.0
Enter the width of the rectangle: 12
Width of the rectangle: 12.0
Area of the rectangle: 1080.0
Output Operations in Python
Output operations in Python involve providing information to the user in a variety of ways, including printing to the console, writing to files, formatting strings, and creating graphical user interfaces (GUIs). When creating our code, we must display the results of specific operations that are executed done in our code. We can do this with the print() method. The complete syntax for the print() function is:
Example 1: Basic Print Statement in Python
The most basic type of output in Python is printing information to the console with the print() function. You can print strings, variables, and expressions as well as modifying the output with formatting choices.
Python3
Example 2: Print Output with End Parameter
In Python, the print() method is used to display output on the console. The end logic allows you define the character(s) that will show up at the end of the output. The default value for end is '\n', which represents that the output will end with a newline character. You may change this behavior by providing a different value to the end argument. Here's how to use the end parameter in the print() function:
In this example, all print() commands have the end logic changed to a space''. Therefore, each following print() call will link its results to the same line without creating a new one. Finally, the output ends with a space because of the last print() statement's end option, which defaults to '\n'.
Python3
# Print multiple values on the same line
print("Hello", end=" ")
print("world!", end=" ")
print("How", end=" ")
print("are", end=" ")
print("you?", end=" ")
OutputHello world! How are you?
Example 3: Printing Output with Separator Parameter
In Python, the print() process has a sep option that allows you to provide a separator between multiple values given to the print() function. By default, sep is set to a single space character'', suggesting that the values supplied to print() are separated by spaces. You may change this behavior by changing the sep logic to a different value.
In this example, the sep claim is set to ", ", " - ", and " | " for every print() command. As a result, the values given to print() are separated by commas, hyphens, and vertical bars, instead of a normal single space character. You can use the sep option to change the formatting of your output and include any text as a separator between data. This allows you to format the output exactly as you want.
Python3
# Print multiple values with a custom separator
print("red", "blue", "grey", sep=", ")
print("one", "two", "three", sep=" - ")
print("Python", "Java", "C++", sep=" | ")
Outputred, blue, grey
one - two - three
Python | Java | C++
Example 4: Print Output with f-String
In Python, you can use format strings to change the output of the print() command. Format strings allow you to include variables and expressions within a string without describing how they should be formatted. To make use of format strings for output operations in Python, perform the following instructions:
In this example, below code sets variables for name, age, and height, then showcases three methods to format and print them: using format string, f-strings, and format string with custom formatting options. Each method outputs a formatted string displaying the values.
Python3
# Define variables
name = "Rahul"
age = 30
height = 175.5
# Using format string
print("Name: {}, Age: {}, Height: {}".format(name, age, height))
# Using f-string (Python 3.6+)
print(f"Name: {name}, Age: {age}, Height: {height}")
# Using format string with formatting options
print("Name: {:10s}, Age: {:3d}, Height: {:.2f}".format(name, age, height))
OutputName: Rahul, Age: 30, Height: 175.5
Name: Rahul, Age: 30, Height: 175.5
Name: Rahul , Age: 30, Height: 175.50
Frequently Asked Questions (FAQ)
How do you input a value into a string in Python?
The str() method in Python converts an integer to a string. For example, if you have a = 3 and want to convert it to a string, simply type a = str(3).
How do you get the output of a string in Python?
Take user input from the keyboard using the built-in function input(). Print output to the console using the built-in method print(). Use Python's f-strings to format string data.
Learn Python from scratch with our Python Full Course Online, designed for beginners and advanced learners alike. Master everything from Python basics to advanced python concepts with hands-on practice and projects.
Take the Three 90 Challenge! Finish 90% of the course in 90 days, and receive a 90% refund. Stay on track, keep progressing, and get rewarded for your hard work.
Start today and become a Python pro!
Similar Reads
Python String Input Output
Python's print() method is used to show program output, whereas the input() function is used for collecting user input. Python starts to accept all input as strings; other data types require specific conversion. We will learn the fundamental input/output processes in Python in this tutorial. We'll t
6 min read
List of strings in Python
A list of strings in Python stores multiple strings together. In this article, we’ll explore how to create, modify and work with lists of strings using simple examples. Creating a List of StringsWe can use square brackets [] and separate each string with a comma to create a list of strings. [GFGTABS
2 min read
Get User Input in Loop using Python
In Python, for and while loops are used to iterate over a sequence of elements or to execute a block of code repeatedly. When it comes to user input, these loops can be used to prompt the user for input and process the input based on certain conditions. In this article, we will explore how to use fo
3 min read
Python | Insert a number in string
Inserting a number into a string in Python can be accomplished using multiple methods, depending on the desired format and style. Techniques like string concatenation, the % operator, and the str.format() method provides flexible and efficient ways to embed numbers within strings. Using String Conca
2 min read
Write Os.System Output In File Using Python
Python is a high-level programming language. There are many modules. However, we will use os.system module in this Program. This module provides a portable way of using operating system-dependent functionality. The "os" and "os.path()" modules include many functions to interact with the file system.
3 min read
Create a List of Strings in Python
Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
3 min read
Output of Python Program | Set 1
Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
3 min read
Output of Python program | Set 5
Predict the output of the following programs: Program 1: [GFGTABS] Python def gfgFunction(): "Geeksforgeeks is cool website for boosting up technical skills" return 1 print (gfgFunction.__doc__[17:21]) [/GFGTABS]Output: coolExplanation: There is a docstring defined for this method,
3 min read
Output of Python programs | Set 8
Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within
3 min read
Print Output from Os.System in Python
In Python, the os.system() function is often used to execute shell commands from within a script. However, capturing and printing the output of these commands can be a bit tricky. This article will guide you through the process of executing a command using os.system() and printing the resulting valu
3 min read
Output of Python programs | Set 7
Prerequisite - Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1[GFGTABS] Python var1 = 'Hello Geeks!' var2 = "GeeksforGeeks" print "var1[0]: ",
3 min read
List With Single Item in Python
Creating a list with single item is quite simple. Let's see different methods to create a single-item list and observe some common mistakes while creating this list. Using Square BracketsThe most simple way to create a list with single element is by using [ ]. [GFGTABS] Python # Creating a list with
2 min read
How to Take Multiple Inputs Using Loop in Python
Taking multiple inputs in Python is a common task, especially when dealing with user interactions or processing data sets. Using a for loop can simplify the process and make the code more efficient. In this article, we will explore simple and commonly used methods to take multiple inputs in Python u
3 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 Variable into a String - Python
In Python, inserting a variable inside a string is a common task. There are different ways to do this depending on which method you find easiest. Let’s look at some simple methods to insert variables into strings. Using + OperatorThe simplest way to insert a variable into a string is by using the +
1 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
Python program to input a comma separated string
Given an input string that is comma-separated instead of space. The task is to store this input string in a list or variables. This can be achieved in Python using two ways: Using List comprehension and split()Using map() and split() Method 1: Using List comprehension and split() split() function he
3 min read
How to Input a List in Python using For Loop
Taking list as input using a for loop is a simple and commonly used method. It allows us to take multiple inputs from the user one by one and store them in a list. This approach provides flexibility and works well when we know the number of elements we need to input. Let’s start with a basic way to
2 min read
Output of Python program | Set 15 (Loops)
Prerequisite - Loops in Python Predict the output of the following Python programs. 1) What is the output of the following program? [GFGTABS] Python x = ['ab', 'cd'] for i in x: i.upper() print(x) [/GFGTABS]Output:['ab', 'cd']Explanation: The function upper() does not modify a string
2 min read