Python打印根号时报类型错误:无法转换字节类型
解决Python打印时的字节类型错误
错误原因
你的代码里使用了u"\u221A".encode('utf-8'),这会生成**字节类型(bytes)**的数据。在Python 3中,print函数不能同时输出整数和字节类型的内容,混合输出就会触发类型错误。而Techsmart使用的可能是Python 2,Python 2对字节和字符串的处理逻辑不同,所以能正常运行。
修复方案
去掉.encode('utf-8'),直接使用Unicode字符串即可。Python 3默认支持Unicode字符串,直接打印"\u221A"就能正确显示根号符号。
修正后的代码
import math square = [] perfect_squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225] num = int(input("")) for i in perfect_squares: if num % i == 0: square.append(i) coefficient = max(square) radicand = num // coefficient coefficient = int(math.sqrt(coefficient)) if num in perfect_squares: print(int(math.sqrt(num))) elif coefficient == 1: print("\u221A", num, sep='') else: print(coefficient, "\u221A", radicand, sep='')
内容的提问来源于stack exchange,提问作者sofiatheshark
相关产品推荐
相关产品推荐

