Python Output: How to Control and Format the Print Function
In Python, the print() function is your primary tool for displaying output to the screen. But did you know you don’t just have to print text on separate lines? Python gives you powerful, built-in parameters to control exactly how your output looks.
(H2)] 1. Basic Output (A Quick Recap)
By default, every time you call the print() function, Python prints your text and automatically moves down to the next line.
print("Python is great!")
print("So easy to learn.")
Output:
Python is great!
So easy to learn.
2. The sep Parameter (Separating Items)
When you print multiple items by separating them with a comma, Python automatically adds a single space between them. However, you can change this behavior using the sep (separator) parameter. You can make it separate items with a dash, a comma, or even no space at all!
# Default separation (a space)
print("2023", "10", "25")
# Custom separation (a dash)
print("2023", "10", "25", sep="-")
# Custom separation (an arrow)
print("Python", "Output", "Guide", sep=" --> ")
Output:
2023 10 25
2023-10-25
Python --> Output --> Guide
3. The end Parameter (Preventing New Lines)
As we saw in the basic example, print() automatically adds a hidden “new line” character at the end. If you want to print multiple statements on the same line, you can use the end parameter to tell Python what to put at the end instead of a new line.
# By default, this would print on two lines
print("Loading", end="...")
print("Complete!")
# You can also use an empty string for no space
print("Hello ", end="")
print("World")
Output:
Loading...Complete!
Hello World
Multi-line Output (Triple Quotes)
If you want to print a long block of text that spans multiple lines, you don’t need to write a dozen print() statements. Instead, use triple quotes (""" or '''). This tells Python to print everything exactly as it is written, including line breaks.
```python
print("""
Welcome to Python!
Start
Options
Quit
""")
**[Paragraph]**
*Output:*
**[SyntaxHighlighter Code block - Language: Plain Text]**
```text
Welcome to Python!
------------------
1. Start
2. Options
3. Quit
Formatted Output (f-strings)
name = "Alice"
score = 95.5
# Using f-string to combine variables and text neatly
print(f"Student: {name}")
print(f"Final Score: {score}%")
# You can even do math inside the brackets!
print(f"Bonus points added: {score + 5}")
Output:
Student: Alice
Final Score: 95.5%
Bonus points added: 100.5
Controlling your output is an essential skill in Python. Whether you are using the sep parameter to format dates, the end parameter to build loading bars, or f-strings to display dynamic data, you now have full control over what appears on the screen. Try mixing these parameters together in your own code to see what you can create!
Please log in to leave a comment.