Type conversion in Python 2.7 vs 3.5, how to make my 2.7 code work under 3.5?
本问题已经有最佳答案,请猛点这里访问。
我将2.7代码移植到3.5中,2.7代码工作正常。在运行2to3并更改旧代码中的明显代码后,我仍然会收到以下错误消息:
1 2 3 4 5 6 7 8 9 10 11 | Exception in thread Thread-7: Traceback (most recent call last): File"C:\Users\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner self.run() File"C:\Users\Anaconda3\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File"<ipython-input-2-eadc3d59ae9f>", line 70, in receiveData nftp = self.parseNFTPData(stringBuffer(data[:-1])) File"<ipython-input-2-eadc3d59ae9f>", line 101, in parseNFTPData current_string += c TypeError: Can't convert 'int' object to str implicitly |
我确实理解这个错误,但是为什么在Python3而不是2下会出现这个错误?在我看来,这是一个语法问题????
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | def parseNFTPData(self, strbuf): quote = False result = [] current_string ="" while not strbuf.eof(): c = strbuf.read() if c ==""": if quote: quote = False else: quote = True elif c =="(" and not quote: list = self.parseNFTPData(strbuf) result.append(list) elif c ==")" and not quote: result.append(self.typeConvert(current_string)) strbuf.read() return result elif len(current_string) > 0 and c =="" and not quote: result.append(self.typeConvert(current_string)) current_string ="" else: current_string += c if len(current_string) > 0: result.append(self.typeConvert(current_string)) return result |
号
"strbuf"属于StringBuffer类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class stringBuffer: def __init__(self, string): self.buffer = string self.readptr = 0 def read(self): if self.readptr < len(self.buffer): readc = self.buffer[self.readptr] self.readptr += 1 else: readc = False return readc def eof(self): if self.readptr >= len(self.buffer): return True else: return False def peek(self): return self.buffer[self.readptr] |
如果
仅供参考,
最可能的原因是
我怀疑这与所做的Unicode更改有关。strbuf是否类似于3.5中的字节字符串?
这可能会起作用。