python exception转字符串,在Python 3中将Exception转换为字符串

博客围绕Python 3.2代码中异常转字符串的问题展开。展示了不同代码示例,如使用`str(e)`和`str(e, encoding = 'utf-8')`的不同结果,还提及含特殊字符时的情况。指出在Python 3.x中`str(e)`可转换异常为字符串,问题可能出在`print()`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

does anyone have an idea, why this Python 3.2 code

try:

raise Exception('X')

except Exception as e:

print("Error {0}".format(str(e)))

works without problem (apart of unicode encoding in windows shell :/),

but this

try:

raise Exception('X')

except Exception as e:

print("Error {0}".format(str(e, encoding = 'utf-8')))

throws TypeError: coercing to str: need bytes, bytearray or buffer-like object, Exception found ?

How to convert an Error to a string with custom encoding?

Edit

It does not works either, if there is \u2019 in message:

try:

raise Exception(msg)

except Exception as e:

b = bytes(str(e), encoding = 'utf-8')

print("Error {0}".format(str(b, encoding = 'utf-8')))

But why cannot str() convert an exception internally to bytes?

解决方案

In Python 3.x, str(e) should be able to convert any Exception to a string, even if it contains Unicode characters.

So unless your exception actually returns an UTF-8 encoded byte array in its custom __str__() method, str(e, 'utf-8') will not work as expected (it would try to interpret a 16bit Unicode character string in RAM as an UTF-8 encoded byte array ...)

My guess is that your problem isn't str() but the print() (i.e. the step which converts the Python Unicode string into something that gets dumped on your console). See this answer for solutions: Python, Unicode, and the Windows console

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值