Python中如何修改print()输出函数(含多返回值)的显示格式?
Hey there! Let's break down your two Python print formatting questions with practical, easy-to-follow examples:
print() function? There are several flexible ways to tweak how print() displays content—here are the most common, useful approaches:
Use the built-in
sepandendparameters
By default,print()separates multiple arguments with spaces and ends with a newline. You can override these to match your needs:# Change the separator between values print(1, 2, 3, sep=" | ") # Output: 1 | 2 | 3 # Replace the default newline ending with something else print("Hi there", end="! ") print("How are you?") # Output: Hi there! How are you?String formatting (f-strings,
str.format(), or old-style%formatting)
For precise control over value display (like decimal places, padding, or text wrapping), use string formatting:pi = 3.14159 # F-strings (Python 3.6+) – the most readable option print(f"Pi rounded to 2 decimals: {pi:.2f}") # Output: Pi rounded to 2 decimals: 3.14 # str.format() method (works for older Python versions) print("Pi rounded to 2 decimals: {:.2f}".format(pi)) # Same output as above # Old-style % formatting (legacy, but still functional) print("Pi rounded to 2 decimals: %.2f" % pi)Create a custom print function
If you want a consistent custom format across your codebase, wrap the built-inprint()with your own logic:def custom_print(*args, sep=" | ", end="\n", file=None): # Example: Convert all inputs to uppercase before printing processed_args = [str(arg).upper() for arg in args] # Call the original print function with modified arguments print(*processed_args, sep=sep, end=end, file=file) custom_print("hello", "python world") # Output: HELLO | PYTHON WORLD
(2, 4)? First, a quick clarification: when a Python function returns multiple values like return x, y, it's actually returning a tuple—that's why print(test()) outputs (2, 4). Here are simple ways to reformat that output:
Unpack the tuple directly in
print()
Use the*operator to unpack the tuple into separate arguments forprint(), then setsepto" and ":def test(): x = 1 + 1 y = 2 + 2 return x, y print(*test(), sep=" and ") # Output: 2 and 4This works for tuples of any length—if your function returns 3 values, it'll automatically output
a and b and c.Unpack and format with f-strings
If you need to reuse the returned values later, unpack them first then format:a, b = test() print(f"{a} and {b}") # Output: 2 and 4This is great for readability and gives you access to
aandbfor other code logic.String join for variable-length tuples
For tuples where the number of elements might change, convert each element to a string and join them:result = test() print(" and ".join(map(str, result))) # Output: 2 and 4This works seamlessly whether your function returns 2, 3, or more values.
内容的提问来源于stack exchange,提问作者Lis

