Python将字符串转换为float或int动态

时间:2014-03-07 13:26:48

标签: python int

我有一个字符串,我必须根据情况转换为int或float:

What I have    => What I want
"548189848.54" => 548189848.54
"548189848.50" => 548189848.5
"548189848.00" => 548189848

有可能吗?

谢谢,

史蒂夫

9 个答案:

答案 0 :(得分:1)

也许你可以转换为float然后使用round

inputs = [ "548189848.54", "548189848.50", "548189848.00" ]

for i in inputs:
    f = float(i)
    if round(f) == f:
        print int(f)
    else:
        print f

输出:

548189848.54
548189848.5
548189848

您也可以使用列表理解来执行相同的操作,例如:

print [int(float(i)) if round(float(i)) == float(i) else float(i) for i in inputs]

输出:

[548189848.54, 548189848.5, 548189848]

答案 1 :(得分:1)

这是应该做的一行。

numbers = ["548189848.54", "548189848.50", "548189848.00"]
result = [int(float(x)) if int(float(x)) == float(x) else float(x)  for x in numbers]

提供输出:

print result
[548189848.54, 548189848.5, 548189848]

答案 2 :(得分:0)

你必须这样做:

a = float("548189848.54")
a = int(a) if abs(int(a) - a) == 0 else a

答案 3 :(得分:0)

num_str = "548189848.54"

if '.' in num_str:
    num = float(num_str)
else:
    num = int(num_str)

答案 4 :(得分:0)

str_a = "23423.00"

a = float(str_a)
if a % 1.0 == 0:
    a = int(a)

答案 5 :(得分:0)

如果你试图用Python浮点数做任何事情,你可能会得到很多浮点精度错误。我建议使用Decimal模块:

from decimal import Decimal, getcontext
getcontext().prec = 30 # alterable, default 28
notInt = Decimal("100.000000000000000000000001")
isInt = Decimal("100.0000000000000000000000000")
if (notInt == int(notInt)):
    notInt = int(notInt)
else:
    notInt = float(notInt)

if (isInt == int(isInt)):
    isInt = int(isInt)
else:
    isInt = float(isInt)

>>> type(isInt)
<type 'int'>
>>> type(notInt)
<type 'float'>

浮点错误的说明:

>>> 5.0000000000000001 == 5
True

答案 6 :(得分:0)

这是一个复杂的脚本,我用于类似的东西。它使用了Decimal

import decimal

def remove_zeros(num):
    """
    1.100000 --> 1.1
    1.0      --> 1
    1.010    --> 1.01
    0.0      --> 0
    000.0000 --> 0
    """
    num = str(num)
    try:
        dec = decimal.Decimal(num)
    except:
        raise Exception("Not a valid floating point or integer")
    tup = dec.as_tuple()
    delta = len(tup.digits) + tup.exponent
    digits = ''.join(str(d) for d in tup.digits)
    if delta <= 0:
        zeros = abs(tup.exponent) - len(tup.digits)
        val = '0.' + ('0'*zeros) + digits
    else:
        val = digits[:delta] + ('0'*tup.exponent) + '.' + digits[delta:]
    val = val.rstrip('0')
    if val[-1] == '.':
        val = val[:-1]
    if tup.sign:
        return '-' + val
    return val

更新:@Cyber​​已经分享了我找不到的相关SO帖子。

答案 7 :(得分:0)

为什么不必要地涉及一些正则表达式?

import re

def float_or_int(s):
    m = re.match('([+-]?\d+)(?:\.(?:0+|$)|$)', s)
    if m:
        return int(m.group(1))
    else:
        return float(s)

举例:

strings = ("548189848.54", "548189848.50", "548189848.00")
map(float_or_int, strings)
# [548189848.54, 548189848.5, 548189848]

答案 8 :(得分:0)

这也支持列表: https://gist.github.com/pschwede/8d0f9d5f632c2f1fae17

def to_value(string):
    """Converts a string to the value it represents.
    If a non-string has been given, it stays as it is.

    Examples:
        >>> to_value("foobar")
        "foobar"
        >>> to_value(12345)
        12345
        >>> to_value("12345")
        12345
        >>> to_value("3.1415")
        3.1415
        >>> to_value("1,2,1")
        [1, 2, 1]
        >>> to_value("1,a,.5")
        [1, "a", 0.5]
    """
    # try if converting int/float back to str looks equal to the original
    # string. Return the string otherwise.
    for type_ in [int, float]:
        try:
            return type_(string)
        except ValueError:
            continue

    # if there is a comma, it must be a list
    try:
        if "," in string:
            return [to_value(s) for s in string.split(",") if s]
    except AttributeError:
        # It's not splittable. Not a string.
        return string
    except TypeError:
        # It's not iterable. Unknown type.
        return string

    # Getting here means the string couldn't be converted to something else.
    # We will return a string then.
    return string