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

Python代码中\n转义字符无法实现换行,问题求助

Python中Account类deposit方法\n转义字符未生效问题解决

问题场景

编写了如下Account类,其中deposit方法返回的字符串包含\n转义字符以实现换行,但执行调用代码后,输出显示原始的\n字符而非实际换行。

类代码

class Account():
    
    def __init__(self, owner, balance = 0.0):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        return (f'{amount} dollars has been deposited to your account. \nYou have {self.balance} dollars.') 
    
    def withdraw(self, amount):
        if amount > self.balance:
            print(f"Insufficient balance. You have {self.balance} dollars.") 
        else:
            self.balance -= amount
            print(f"Left balance is: {self.balance}") 
    def __str__(self):
        return (f"Account's holder: {self.owner}\nBalance: {self.balance}")

调用代码

acct1 = Account('Jose',100)
acct1.deposit(50)

实际输出

'50 dollars has been deposited to your account. \nYou have 150 dollars.'

问题原因

在Python交互式环境(如Python Shell、Jupyter Notebook)中,直接调用返回字符串的函数时,解释器会默认输出该字符串的**repr()**表示形式——这是字符串的“原始格式”,会保留引号和转义字符,不会解析\n为换行。

解决方法

方法1:用print()包裹调用

print函数会自动解析字符串中的转义字符,渲染出换行效果:

acct1 = Account('Jose',100)
print(acct1.deposit(50))

执行后输出:

50 dollars has been deposited to your account. 
You have 150 dollars.

方法2:修改deposit方法为直接打印

将deposit方法的return改为print,调用时直接执行就能输出换行内容:

class Account():
    # 其他方法保持不变
    def deposit(self, amount):
        self.balance += amount
        print(f'{amount} dollars has been deposited to your account. \nYou have {self.balance} dollars.') 

调用代码无需修改,执行后直接输出换行后的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57