【问题标题】:Convert "numeric" string into some number type in Python without lose information在 Python 中将“数字”字符串转换为某种数字类型而不会丢失信息
【发布时间】:2016-01-17 16:47:24
【问题描述】:

我正在创建一个复合字符串来记忆 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。

如果我想返回像浮点数这样的数字类型,主要问题来了。

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

【问题讨论】:

  • 我不确定你的意思。要将字符串'1.20' 转换为不是1.2float 吗?
  • 为什么需要它作为浮点数?
  • @RedVelvet 你不能保留零 - 1.20 与 1.200 完全相同
  • 你不能那样做。 1.20 在数学上等价于 1.2
  • 你的两部分 id 不是一个单一的数字,所以不要试图把它当作一个。将其作为两个数字字段或单个字符串存储在数据库中。在需要时将字符串拆分为两个数字很容易。

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


【解决方案1】:

我的猜测是你需要表示版本,在这种情况下你应该看看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)

【讨论】:

  • 这是有道理的,但问题是如何将这些值存储为数字,而不是字符串,同时保留尾随零。
【解决方案2】:

尝试另一种存储方式

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

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

【讨论】:

    【解决方案3】:

    尝试使用 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 2015-06-05
      相关资源
      最近更新 更多