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

如何让Python函数返回的多行格式化字符串正常换行显示?

解决Python多行f-string输出带转义字符问题
  • 核心问题:直接在交互式环境返回字符串(而非用print()输出)时,Python会显示字符串的repr形式(带引号和\n转义符);若手动拼接\n时误加多余空格,也会导致输出混乱。

正确写法与解决步骤

  1. 用三引号定义多行f-string
    用三引号("""或''')包裹内容,自动保留换行和格式,避免手动加\n的错误:
    import pandas as pd
    
    def calculate_investment(df):
        total_invested = df['invest'].sum()
        total_profit = df['profit'].sum()
        rate = (total_profit / total_invested) * 100
    
        # 三引号多行f-string,直接按预期格式编写
        result = f"""Invested Amount: ${total_invested:,.2f}
    

Total Profit: ${total_profit:,.2f}
Return Rate: {rate:.2f}%"""
return result

测试代码

test_df = pd.DataFrame({'invest': [5000, 3000], 'profit': [750, 450]})
output = calculate_investment(test_df)
print(output) # 用print()输出,自动解析换行符

运行后会正常分行显示:

Invested Amount: $8,000.00
Total Profit: $1,200.00
Return Rate: 15.00%

2. **避免交互式环境直接返回字符串**
在Jupyter或Python shell中,直接输入`output`会显示带`\n`的repr格式:

'Invested Amount: $8,000.00\nTotal Profit: $1,200.00\nReturn Rate: 15.00%'

此时必须用`print(output)`,或在Jupyter中导入`from IPython.display import Markdown`后用`display(Markdown(output))`来正确渲染换行。

3. **清理多余空格**
若手动添加`\n`,注意`\n`后不要加多余空格,否则每行开头会出现空格:
```python
# 错误写法(\n后带空格)
bad_result = f"Invested Amount: ${total_invested:,.2f}\n Total Profit: ${total_profit:,.2f}"
# 正确写法(\n后无空格)
good_result = f"Invested Amount: ${total_invested:,.2f}\nTotal Profit: ${total_profit:,.2f}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:22:35