转换"数字"在Python中使用某种数字类型的字符串而不会丢失信息

时间:2015-10-19 11:01:59

标签: python string python-2.7 casting floating-point

我正在为memorize id和sub id创建一个复合字符串,如下所示:

1.1

1.2

1.3

以这种方式:

 main_id=1 #not related to sub_id
 sub_id= 1 #or more by increment
 item = str(main_id)+"."+str(sub_id))

当我将数字传递给字符串时,它很有效。保持零。 示例:1并使用数字i可以增加子字符串而没有任何问题。 1.1 - > 1.2 - > 1.19 - > 1.20 - 如果我使用浮动,则不是2.0。

如果我想返回像float这样的数字类型,那么主要问题就出现了。

有一些方法可以返回数字类型(浮点数或其他类型)并保留字符串内容而不会丢失任何信息吗?

3 个答案:

答案 0 :(得分:0)

我的猜测是你需要代表版本,在这种情况下你应该看一下distutils.version模块:

Type:        module
String form: <module 'distutils.version' from 
                '/usr/lib/python2.7/distutils/version.pyc'>
File:        /usr/lib/python2.7/distutils/version.py
Docstring:
Provides classes to represent module version numbers (one class for
each style of version numbering).  There are currently two such classes
implemented: StrictVersion and LooseVersion.

Every version number class implements the following interface:
  * the 'parse' method takes a string and parses it to some internal
    representation; if the string is an invalid version number,
    'parse' raises a ValueError exception
  * the class constructor takes an optional string argument which,
    if supplied, is passed to 'parse'
  * __str__ reconstructs the string that was passed to 'parse' (or
    an equivalent string -- ie. one that will generate an equivalent
    version number instance)
  * __repr__ generates Python code to recreate the version number instance
  * __cmp__ compares the current instance with either another instance
    of the same class or a string (which will be parsed to an instance
    of the same class, thus must follow the same rules)

答案 1 :(得分:0)

尝试另一种方式来存储它

实施例。对于'1.20',您可以将其存储为float('1.02'),将'1.200'存储为float('1.002')

只需反转sub_id,因为sub_id不以零开头。

答案 2 :(得分:0)

尝试使用python中的十进制模块,例如:

from decimal import Decimal

[In]: Decimal("1.1")
[Out]: Decimal('1.1')

[In]: Decimal("1.10")
[Out]: Decimal('1.10')

[In]: Decimal("1.20")
[Out]: Decimal('1.20')