之间有什么区别__str__和__repr__在__str__?
我有一个格式的字符串:Python中的'nn.nnnnn',我想将它转换为整数.
直接转换失败:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法将其转换为十进制:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
Run Code Online (Sandbox Code Playgroud)
我也可以拆分'.',然后从零中减去小数,然后将其添加到整数......哎呀.
但我更喜欢把它作为一个int,没有不必要的类型转换或机动.