You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何修改print()输出函数(含多返回值)的显示格式?

Hey there! Let's break down your two Python print formatting questions with practical, easy-to-follow examples:

1. How to customize the output format of Python's print() function?

There are several flexible ways to tweak how print() displays content—here are the most common, useful approaches:

  • Use the built-in sep and end parameters
    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-in print() 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. How to display a function's multi-value return as "2 and 4" instead of (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 for print(), then set sep to " and ":

    def test():
        x = 1 + 1
        y = 2 + 2
        return x, y
    
    print(*test(), sep=" and ")  # Output: 2 and 4
    

    This 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 4
    

    This is great for readability and gives you access to a and b for 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 4
    

    This works seamlessly whether your function returns 2, 3, or more values.


内容的提问来源于stack exchange,提问作者Lis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:37:36