简体   繁体   English

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

[英]Python Convert string to float or int dynamically

I have a string that I have to convert into int or float depending or the case : 我有一个字符串,我必须转换为int或浮动依赖或案例:

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

Is it possible to do it ? 有可能吗?

Thanks, 谢谢,

Steve 史蒂夫

Maybe you could convert to float and then use round : 也许你可以转换为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

output: 输出:

548189848.54
548189848.5
548189848

You could also do the same thing using a list comprehension, like: 你也可以使用列表理解做同样的事情,比如:

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

output: 输出:

[548189848.54, 548189848.5, 548189848]

Here's a one line that should do it. 这是应该做的一行。

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

Gives output: 给出输出:

print result
[548189848.54, 548189848.5, 548189848]

You just have to do that: 你必须这样做:

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

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

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

You'll probably get a lot of floating point precision errors if you try to do anything with Python floats. 如果你试图用Python浮点数做任何事情,你可能会得到很多浮点精度错误。 I suggest using the Decimal module: 我建议使用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'>

An illustration of the floating point errors: 浮点错误的说明:

>>> 5.0000000000000001 == 5
True

That is a complex script that I used for similar stuff. 这是一个复杂的脚本,我用于类似的东西。 It used Decimal 它使用了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

Update: @Cyber already shares the related SO post, which I failed to find. 更新:@Cyber​​已经分享了相关的SO帖子,但我没找到。

Why not unnecessarily involve some regex? 为什么不必要地涉及一些正则表达式?

import re

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

With your examples: 用你的例子:

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

This also supports lists: https://gist.github.com/pschwede/8d0f9d5f632c2f1fae17 这也支持列表: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM