Various Ways to Output Values with the print Function
When programming, there are often times when you need to check the value of a variable or verify the result of the code execution.
One of the most frequently used functions to make sure a program is working as intended is print.
In this lesson, we will explore formatting methods to make the output of the print function more organized.
Formatting Using %
In Python, you can use the % operator to neatly insert variable values into a string when outputting.
# Output: Hello, Python print("Hello, %s!" % "Python")
The code above uses %s format code inside the print function.
%s is used for strings, and the value after the % operator is substituted as a string.
To print integers, use %d.
# Output: 3 apples print("%d apples" % 3)
Formatting Multiple Values
When formatting multiple values, use parentheses to list the variables separated by commas, like % (name, age).
name = "GeekHaus" age = 30 # Output: Name: GeekHaus, Age: 30 print("Name: %s, Age: %d" % (name, age))
As mentioned earlier, %s represents a string, and %d stands for an integer.
In the example above, %s is substituted with the string "GeekHaus", and %d is replaced with the integer 30.
To format floating-point numbers, use %f.
Using f-strings
Since Python 3.6, a new string formatting method called f-string has been introduced.
With f-strings, you can directly include variable names and expressions inside curly braces { } by prefixing the string with f.
name = "GeekHaus" age = 30 print(f"Name: {name}, Age: {age}")
The code above prints Name: GeekHaus, Age: 30.
f-strings are preferred by many Python developers because they enhance readability and make the code concise.
Additionally, with f-strings, you can call functions inside the curly braces, like f"{name.upper()}".
Note: The
upper()function converts all letters in a string to uppercase.
Other Printing Methods
Printing Without New Line
By default, the print function adds a newline after output.
For example, the following code prints 1, 2, 3 on separate lines.
print(1) print(2) print(3)
If you want to print without a newline, you can use the end parameter.
print(1, end=" ") print(2, end=" ") print(3)
1 2 3
In the code above, end=" " sets a space (" ") instead of a newline after printing each value.
Setting Separators Between Variables
To print multiple values separated by a specific character, use the sep (Separator) parameter.
print("Python", "coding", "is fun", sep="-")
Python-coding-is fun
In the code above, sep="-" sets - as the separator between the values to be printed.
Setting Separators Between Variables
Complete the example to print a string separated by -. Expected output: apple-banana-cherry
a = 'apple'b = 'banana'c = 'cherry'print(a, b, c, sep=)Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result