The print()
function in Python provides several ways to format the output, making it more readable and organized. These formatting techniques can be particularly useful when working with conditional statements and displaying dynamic data.
One way to format the output of the print()
function is by using string formatting. Python supports several string formatting methods, including the classic %
operator, the format()
method, and f-strings (introduced in Python 3.6).
Here's an example using the %
operator:
name = "LabEx"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is LabEx and I am 25 years old.
And here's an example using the format()
method:
name = "LabEx"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is LabEx and I am 25 years old.
Finally, here's an example using f-strings:
name = "LabEx"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is LabEx and I am 25 years old.
All of these methods allow you to insert values into a string in a more readable and structured way, making your code more maintainable and easier to understand.
Aligning and Padding Output
You can also use the print()
function to align and pad the output, making it more visually appealing. This can be particularly useful when displaying tabular data or when you need to ensure that the output is consistently formatted.
Here's an example of right-aligning and padding the output:
name = "LabEx"
age = 25
print(f"{name:>20} is {age:>3} years old.")
Output:
LabEx is 25 years old.
In this example, the name is right-aligned within a 20-character field, and the age is right-aligned within a 3-character field.
You can also use the <
and ^
alignment specifiers to left-align and center-align the output, respectively.
Controlling Spacing and Newlines
The print()
function also allows you to control the spacing and newlines in the output. You can use the sep
and end
parameters to customize the behavior.
Here's an example of using sep
to change the separator between values:
name = "LabEx"
age = 25
print(name, age, sep=", ")
Output:
LabEx, 25
And here's an example of using end
to change the character that terminates the printed line:
print("Hello", end="")
print("World")
Output:
HelloWorld
By mastering these formatting techniques, you can create more readable and visually appealing output in your Python programs, especially when working with conditional statements and dynamic data.