Customizing Print Behavior
Modifying Print Separator
Basic Separator Customization
## Default separator (space)
print("Python", "Java", "C++")
## Custom separator
print("Python", "Java", "C++", sep=" | ")
Controlling Line Endings
Suppressing Newline
## Default behavior (newline)
print("Processing")
print("Complete")
## Custom end parameter
print("Processing", end=" ")
print("complete!")
F-Strings
name = "LabEx"
version = 3.0
print(f"Welcome to {name} version {version}")
## Numeric formatting
price = 49.99
print("Course price: ${:.2f}".format(price))
Redirecting Print Output
Printing to Files
## Write output to a file
with open('output.txt', 'w') as file:
print("Logging data", file=file)
Dynamic Print Modification
Custom Print Function
def custom_print(*args, prefix='[LOG]', **kwargs):
print(prefix, *args, **kwargs)
custom_print("System initialized")
custom_print("Warning message", prefix='[WARN]')
Print Behavior Flow
graph TD
A[Print Input] --> B{Formatting Required?}
B -->|Yes| C[Apply Formatting]
B -->|No| D[Direct Output]
C --> D
D --> E[Destination Check]
E -->|Console| F[Display]
E -->|File| G[Write to File]
Print Customization Options
| Technique | Use Case | Example |
| ---------------- | ---------------------------- | --------------------------- | --- |
| Separator | Custom item division | sep=' | '
|
| End Parameter | Control line termination | end=' '
|
| F-Strings | Dynamic string interpolation | f"{variable}"
|
| File Redirection | Logging output | print(..., file=log_file)
|
- Minimize complex formatting
- Use built-in methods for efficiency
- Consider logging for extensive output
Mastering these techniques will enhance your Python printing capabilities in LabEx projects.